home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / web / cweb.lha / cweb / weave.web (.txt) < prev    next >
Texinfo Document  |  1990-07-13  |  127KB  |  2,751 lines

  1. % Copyright (C) 1987, 1989 Princeton University
  2. % This file is part of CWEB.
  3. % This program by Silvio Levy is based on a program by D. E. Knuth.
  4. % It is distributed WITHOUT ANY WARRANTY, express or implied.
  5. % $Revision: 1.10 $
  6. % $Date: 90/01/22 14:18:17 $
  7. % Here is TeX material that gets inserted after \input webmac
  8. \def\hang{\hangindent 3em\indent\ignorespaces}
  9. \font\ninerm=amr9
  10. \let\mc=\ninerm % medium caps
  11. \def\cee{C}
  12. \def\Pascal{Pascal}
  13. \def\pb{$\.|\ldots\.|$} % C brackets (|...|)
  14. \def\v{\char'174} % vertical (|) in typewriter font
  15. \def\dleft{[\![} \def\dright{]\!]} % double brackets
  16. \mathchardef\RA="3221 % right arrow
  17. \mathchardef\BA="3224 % double arrow
  18. \def\({} % kludge for alphabetizing certain module names
  19. \def\title{CWEAVE $
  20.   ($Revision: 1.10 $)
  21. \def\contentspagenumber{1} % should be odd
  22. \def\topofcontents{\null\vfill
  23.   \titlefalse % include headline on the contents page
  24.   \def\rheader{\hfil}
  25.   \centerline{\titlefont The {\ttitlefont CWEAVE} processor}
  26.   \vskip 15pt
  27.   \centerline{$
  28.     ($Revision: 1.10 $)
  29.     $}
  30.   \vfill}
  31. \pageno=\contentspagenumber \advance\pageno by 1
  32. \let\maybe=\iftrue
  33. @* Introduction.
  34. The ``banner line'' defined here should be changed whenever \.{CWEAVE}
  35. is modified.
  36. @d banner "This is CWEAVE ($Revision: 1.10 $)\n"
  37. @ \.{CWEAVE} has a fairly straightforward outline.  It operates in
  38. three phases: first it inputs the source file and stores cross-reference
  39. data, then it inputs the source once again and produces the \TeX\ output
  40. file, and finally it sorts and outputs the index.  It can be compiled
  41. with certain optional flags, |DEBUG| and |STAT|, the latter being used
  42. to keep track of how much of \.{WEAVE}'s resources were actually used.
  43. @c @<Include files@>@/
  44. @<Common code for \.{WEAVE} and \.{TANGLE}@>@/
  45. @<Typedef declarations@>@/
  46. @<Global variables@>@/
  47. main (ac, av)
  48. char **av;
  49.   argc=ac; argv=av;
  50.   program=weave;
  51.   common_init();
  52.   @<Set initial values@>;
  53.   printf(banner); /* print a ``banner line'' */
  54.   @<Store all the reserved words@>;
  55.   phase_one(); /* read all the user's text and store the cross-references */
  56.   phase_two(); /* read all the text again and translate it to \TeX\ form */
  57.   phase_three(); /* output the cross-reference index */
  58.   wrap_up();
  59. @ The following parameters were sufficient in the original \.{WEAVE} to
  60. handle \TeX, so they should be sufficient for most applications of \.{CWEAVE}.
  61. If you change |max_bytes|, |max_names|, |hash_size| or |buf_size|
  62. you have to change them also in the file |"common.web"|.
  63. @d max_bytes 90000 /* the number of bytes in identifiers,
  64.   index entries, and module names */
  65. @d max_names 4000 /* number of identifiers, strings, module names;
  66.   must be less than 10240; used in |"common.web"| */
  67. @d max_modules 2000 /* greater than the total number of modules */
  68. @d hash_size 353 /* should be prime */
  69. @d buf_size 100 /* maximum length of input line, plus one */
  70. @d longest_name 400 /* module names and strings shouldn't be longer than this */
  71. @d long_buf_size 500 /* |buf_size+longest_name| */
  72. @d line_length 80 /* lines of \TeX\ output have at most this many characters;
  73.   should be less than 256 */
  74. @d max_refs 20000 /* number of cross-references; must be less than 65536 */
  75. @d max_toks 20000 /* number of symbols in \cee\ texts being parsed;
  76.   must be less than 65536 */
  77. @d max_texts 2000 /* number of phrases in \cee\ texts being parsed;
  78.   must be less than 10240 */
  79. @d max_scraps 1000 /* number of tokens in \cee\ texts being parsed */
  80. @d stack_size 400 /* number of simultaneous output levels */
  81. @i common.h
  82. @* Data structures exclusive to {\tt WEAVE}.
  83. As explained in \.{common.web}, the field of a |name_info| structure
  84. that contains the |rlink| of a module name is used for a completely
  85. different purpose in the case of identifiers.  If is then called the
  86. |ilk| of the identifier, and it is used to
  87. distinguish between various types of identifiers, as follows:
  88. \yskip\hang |normal| identifiers are part of the \cee\ program and
  89. will appear in italic type.
  90. \yskip\hang |roman| identifiers are index entries that appear after
  91. \.{@@\^} in the \.{WEB} file.
  92. \yskip\hang |wildcard| identifiers are index entries that appear after
  93. \.{@@:} in the \.{WEB} file.
  94. \yskip\hang |typewriter| identifiers are index entries that appear after
  95. \.{@@.} in the \.{WEB} file.
  96. \yskip\hang |case_like|, \dots, |typedef_like|
  97. identifiers are \cee\ reserved words whose |ilk| explains how they are
  98. to be treated when \cee\ code is being formatted.
  99. @d ilk dummy.Ilk
  100. @d normal 0 /* ordinary identifiers have |normal| ilk */
  101. @d roman 1 /* normal index entries have |roman| ilk */
  102. @d wildcard 2 /* user-formatted index entries have |wildcard| ilk */
  103. @d typewriter 3 /* `typewriter type' entries have |typewriter| ilk */
  104. @d reserved(a) (a->ilk>typewriter) /* tells if a name is a reserved word */
  105. @d do_like 55 /* \&{do} */
  106. @d if_like 57 /* \&{if}, \&{while}, \&{for}, \&{switch}, \&{ifdef},
  107. \&{ifndef}, \&{endif} */
  108. @d int_like 58 /* \&{int}, \&{char}, \&{extern}, \dots  */
  109. @d case_like 59 /* \&{return}, \&{goto}, \&{break}, \&{continue} */
  110. @d sizeof_like 60 /* \&{sizeof} */
  111. @d struct_like 61 /* \&{struct} */
  112. @d typedef_like 62 /* \&{typedef} */
  113. @d define_like 63 /* \&{define} */
  114. @d parms_like 56 /* \&{PARMS} */
  115. @ We keep track of the current module number in |module_count|, which
  116. is the total number of modules that have started.  Modules which have
  117. been altered by a change file entry have their |changed_module| flag
  118. turned on during the first phase.
  119. @<Global...@>=
  120. boolean change_exists; /* has any module changed? */
  121. @ The other large memory area in \.{CWEAVE} keeps the cross-reference data.
  122. All uses of the name |p| are recorded in a linked list beginning at
  123. |p->xref|, which points into the |xmem| array. The elements of |xmem|
  124. are structures consisting of an integer, |num|, and a pointer |xlink|
  125. to another element of |xmem|.  If |x=p->xref| is a pointer into |xmem|,
  126. the value of |x->num| is either a module number where |p| is used,
  127. or it is |def_flag| plus a module number where |p| is defined;
  128. and |x->xlink| points to the next such cross-reference for |p|,
  129. if any. This list of cross-references is in decreasing order by
  130. module number. The next unused slot in |xmem| is |xref_ptr|.
  131. The global variable |xref_switch| is set either to |def_flag| or to zero,
  132. depending on whether the next cross-reference to an identifier is to be
  133. underlined or not in the index. This switch is set to |def_flag| when
  134. \.{@@!} or \.{@@d} or \.{@@f} is scanned, and it is cleared to zero when
  135. the next identifier or index entry cross-reference has been made. Similarly,
  136. the global variable |mod_xref_switch| is either |def_flag| or zero, depending
  137. on whether a module name is being defined or used.
  138. @<Type...@>=
  139. typedef struct xref_info {
  140.   sixteen_bits num; /* module number plus zero or |def_flag| */
  141.   struct xref_info *xlink; /* pointer to the previous cross-reference */
  142. } xref_info;
  143. typedef xref_info *xref_pointer;
  144. @ @<Global...@>=
  145. xref_info xmem[max_refs]; /* contains cross-reference information */
  146. xref_pointer xmem_end = xmem+max_refs-1;
  147. xref_pointer xref_ptr; /* the largest occupied position in |xmem| */
  148. sixteen_bits xref_switch,mod_xref_switch; /* either zero or |def_flag| */
  149. @ @d def_flag 10240 /* must be strictly larger than |max_modules| */
  150. @d xref equiv_or_xref
  151. @<Set init...@>=
  152. xref_ptr=xmem; name_dir->xref=(char*)xmem; xref_switch=0; mod_xref_switch=0;
  153. xmem->num=0; /* cross-references to undefined modules */
  154. @ A new cross-reference for an identifier is formed by calling |new_xref|,
  155. which discards duplicate entries and ignores non-underlined references
  156. to one-letter identifiers or \cee's reserved words.
  157. If the user has sent the |no_xref| flag (the \.{-x} option of the command line),
  158. it is unnecessary to keep track of cross-references for identifers.
  159. If one were careful, one could probably make more changes around module
  160. 100 to avoid a lot of identifier looking up.
  161. @d append_xref(c) if (xref_ptr==xmem_end) overflow("cross-reference")@;
  162.   else (++xref_ptr)->num=c;
  163. @c new_xref(p)
  164. name_pointer p;
  165.   xref_pointer q; /* pointer to previous cross-reference */
  166.   sixteen_bits m, n; /* new and previous cross-reference value */
  167.   if (no_xref) return;
  168.   if ((reserved(p) || length(p)==1) && xref_switch==0) return;
  169.   m=module_count+xref_switch; xref_switch=0; q=(xref_pointer)p->xref;
  170.   if (q != xmem) {
  171.     n=q->num;
  172.     if (n==m || n==m+def_flag) return;
  173.     else if (m==n+def_flag) {
  174.     q->num=m; return;
  175.     }
  176.   append_xref(m); xref_ptr->xlink=q; p->xref=(char*)xref_ptr;
  177. @ The cross-reference lists for module names are slightly different. Suppose
  178. that a module name is defined in modules $m_1$, \dots, $m_k$ and used in
  179. modules $n_1$, \dots, $n_l$. Then its list will contain $m_1+|def_flag|{}$,
  180. $m_k+|def_flag|{}$, \dots, $m_2+|def_flag|{}$, $n_l$, \dots, $n_1$, in
  181. this order.  After Phase II, however, the order will be
  182. $m_1+|def_flag|{}$, \dots, $m_k+|def_flag|{}$, $n_1$, \dots, $n_l$.
  183. @c new_mod_xref(p)
  184. name_pointer p;
  185.   xref_pointer q,r; /* pointers to previous cross-references */
  186.   q=(xref_pointer)p->xref; r=xmem;
  187.   if (q>xmem) {
  188.     if (mod_xref_switch==0) while (q->num>=def_flag) {
  189.       r=q; q=q->xlink;
  190.     }
  191.     else if (q->num>=def_flag) {
  192.       r=q; q=q->xlink;
  193.     }
  194.   append_xref(module_count+mod_xref_switch);
  195.   xref_ptr->xlink=q; mod_xref_switch=0;
  196.   if (r==xmem) p->xref=(char*)xref_ptr;
  197.   else r->xlink=xref_ptr;
  198. @ A third large area of memory is used for sixteen-bit `tokens', which appear
  199. in short lists similar to the strings of characters in |byte_mem|. Token lists
  200. are used to contain the result of \cee\ code translated into \TeX\ form;
  201. further details about them will be explained later. A |text_pointer| variable
  202. is an index into |tok_start|.
  203. @<Typed...@>=
  204. typedef sixteen_bits token;
  205. typedef token *token_pointer;
  206. typedef token_pointer *text_pointer;
  207. @ The first position of |tok_mem|
  208. that is unoccupied by replacement text is called |tok_ptr|, and the first
  209. unused location of |tok_start| is called |text_ptr|.
  210. Thus, we usually have |tok_start[text_ptr]=tok_ptr|.
  211. @<Global...@>=
  212. token tok_mem[max_toks]; /* tokens */
  213. token_pointer tok_mem_end = tok_mem+max_toks-1; /* end of |tok_mem| */
  214. token_pointer tok_start[max_texts]; /* directory into |tok_mem| */
  215. token_pointer tok_ptr; /* first unused position in |tok_mem| */
  216. text_pointer text_ptr; /* first unused position in |tok_start| */
  217. text_pointer tok_start_end = tok_start+max_texts-1; /* end of |tok_start| */
  218. #ifdef STAT
  219. token_pointer max_tok_ptr; /* largest value of |tok_ptr| */
  220. text_pointer max_text_ptr; /* largest value of |text_ptr| */
  221. #endif STAT
  222. @ @<Set init...@>=
  223. tok_ptr=tok_mem+1; text_ptr=tok_start+1; tok_start[0]=tok_mem+1;
  224. tok_start[1]=tok_mem+1;
  225. #ifdef STAT
  226. max_tok_ptr=tok_mem+1; max_text_ptr=tok_start+1;
  227. #endif STAT
  228. names_match(p,first,l,t)
  229. name_pointer p; /* points to the proposed match */
  230. ASCII *first; /* position of first character of string */
  231. int l; /* length of identifier */
  232. eight_bits t; /* desired ilk */
  233.   if (length(p)!=l) return 0;
  234.   if (p->ilk!=t && !(t==normal && reserved(p))) return 0;
  235.   return !strncmp(first,p->byte_start,l);
  236. init_p(p,t)
  237. name_pointer p;
  238. eight_bits t;
  239.   p->ilk=t; p->xref=(char*)xmem;
  240. init_node(p)
  241. name_pointer p;
  242.   p->xref=(char*)xmem;
  243. @ We have to get \cee's
  244. reserved words into the hash table, and the simplest way to do this is
  245. to insert them every time \.{CWEAVE} is run.  Since there are relatively
  246. few reserved words, we use an ad hoc function to simplify the code.
  247. @^reserved words@>
  248. @<Store all the reserved words@>=
  249. id_lookup("auto",NULL,int_like); id_lookup("break",NULL,case_like);
  250. id_lookup("case",NULL,case_like); id_lookup("char",NULL,int_like);
  251. id_lookup("continue",NULL,case_like); id_lookup("default",NULL,case_like);
  252. id_lookup("define",NULL,define_like);
  253. id_lookup("do",NULL,do_like); id_lookup("double",NULL,int_like);
  254. id_lookup("endif",NULL,if_like); id_lookup("else",NULL,else_like);
  255. id_lookup("enum",NULL,struct_like);
  256. id_lookup("extern",NULL,int_like); id_lookup("FILE",NULL,int_like);
  257. id_lookup("float",NULL,int_like); id_lookup("for",NULL,if_like);
  258. id_lookup("goto",NULL,case_like); id_lookup("if",NULL,if_like);
  259. id_lookup("ifdef",NULL,if_like); id_lookup("ifndef",NULL,if_like);
  260. id_lookup("int",NULL,int_like); id_lookup("long",NULL,int_like);
  261. id_lookup("line",NULL,if_like); id_lookup("include",NULL,if_like);
  262. id_lookup("register",NULL,int_like); id_lookup("return",NULL,case_like);
  263. id_lookup("short",NULL,int_like); id_lookup("sizeof",NULL,sizeof_like);
  264. id_lookup("static",NULL,int_like); id_lookup("struct",NULL,struct_like);
  265. id_lookup("switch",NULL,if_like); id_lookup("typedef",NULL,typedef_like);
  266. id_lookup("union",NULL,struct_like); id_lookup("undef",NULL,if_like);
  267. id_lookup("unsigned",NULL,int_like); id_lookup("while",NULL,if_like);
  268. id_lookup("void",NULL,int_like);
  269. id_lookup("PARMS",NULL,parms_like);
  270. @* Lexical scanning.
  271. Let us now consider the subroutines that read the \.{WEB} source file
  272. and break it into meaningful units. There are four such procedures:
  273. One simply skips to the next `\.{@@\ }' or `\.{@@*}' that begins a
  274. module; another passes over the \TeX\ text at the beginning of a
  275. module; the third passes over the \TeX\ text in a \cee\ comment;
  276. and the last, which is the most interesting, gets the next token of
  277. a \cee\ text.  They all use the pointers |limit| and |loc| into
  278. the line of input currently being studied.
  279. @ Control codes in \.{WEB}, which begin with `\.{@@}', are converted
  280. into a numeric code designed to simplify \.{CWEAVE}'s logic; for example,
  281. larger numbers are given to the control codes that denote more significant
  282. milestones, and the code of |new_module| should be the largest of
  283. all. Some of these numeric control codes take the place of ASCII
  284. control codes that will not otherwise appear in the output of the
  285. scanning routines.
  286. @^ASCII code@>
  287. @d ignore 00 /* control code of no interest to \.{CWEAVE} */
  288. @d verbatim 02 /* extended ASCII alpha will not appear */
  289. @d force_line 03 /* extended ASCII beta will not appear */
  290. @d begin_comment 011 /* ASCII tab mark will not appear */
  291. @d switch_math_flag 0175 /* this code will be intercepted without confusion */
  292. @d underline 0176 /* this code will be intercepted without confusion */
  293. @d param 0177 /* ASCII delete will not appear */
  294. @d xref_roman 0203 /* control code for `\.{@@\^}' */
  295. @d xref_wildcard 0204 /* control code for `\.{@@:}' */
  296. @d xref_typewriter 0205 /* control code for `\.{@@.}' */
  297. @d TeX_string 0206 /* control code for `\.{@@t}' */
  298. @d ascii_constant 0207 /* control code for `\.{@@'}' */
  299. @d join 0210 /* control code for `\.{@@\&}' */
  300. @d thin_space 0211 /* control code for `\.{@@,}' */
  301. @d math_break 0212 /* control code for `\.{@@\v}' */
  302. @d line_break 0213 /* control code for `\.{@@/}' */
  303. @d big_line_break 0214 /* control code for `\.{@@\#}' */
  304. @d no_line_break 0215 /* control code for `\.{@@+}' */
  305. @d pseudo_semi 0216 /* control code for `\.{@@;}' */
  306. @d trace 0220 /* control code for `\.{@@0}', `\.{@@1}' and `\.{@@2}' */
  307. @d format 0223 /* control code for `\.{@@f}' */
  308. @d definition 0224 /* control code for `\.{@@d}' */
  309. @d begin_C 0225 /* control code for `\.{@@c}' */
  310. @d module_name 0226 /* control code for `\.{@@<}' */
  311. @d new_module 0227 /* control code for `\.{@@\ }' and `\.{@@*}' */
  312. @ Control codes are converted from ASCII to \.{CWEAVE}'s internal
  313. representation by means of the table |ccode|.
  314. @<Global...@>=
  315. eight_bits ccode[128]; /* meaning of a char following \.{@@} */
  316. @ @<Set ini...@>=
  317. {int c; for (c=0; c<=127; c++) ccode[c]=0;}
  318. ccode[' ']=ccode[tab_mark]=ccode['*']=new_module;
  319. ccode['@@']='@@'; /* `quoted' at sign */
  320. ccode['=']=verbatim; ccode['\\']=force_line;
  321. ccode['d']=ccode['D']=definition; ccode['f']=ccode['F']=format;
  322. ccode['c']=ccode['C']=begin_C; ccode['t']=ccode['T']=TeX_string;
  323. ccode['&']=join; ccode['<']=module_name;
  324. ccode['!']=underline; ccode['^']=xref_roman;
  325. ccode['$']=switch_math_flag;
  326. ccode[':']=xref_wildcard; ccode['.']=xref_typewriter; ccode[',']=thin_space;
  327. ccode['|']=math_break; ccode['/']=line_break; ccode['#']=big_line_break;
  328. ccode['+']=no_line_break; ccode[';']=pseudo_semi;
  329. ccode['\'']=ascii_constant;
  330. @t\4@>@<Special control codes allowed only when debugging@>@;
  331. @ If \.{CWEAVE} is compiled with debugging commands, one can write
  332. \.{@@2}, \.{@@1}, and \.{@@0} to turn tracing fully on, partly on,
  333. and off, respectively.
  334. @<Special control codes...@>=
  335. #ifdef DEBUG
  336. ccode['0']=ccode['1']=ccode['2']=trace;
  337. #endif DEBUG
  338. @ The |skip_limbo| routine is used on the first pass to skip through
  339. portions of the input that are not in any modules, i.e., that precede
  340. the first module. After this procedure has been called, the value of
  341. |input_has_ended| will tell whether or not a module has actually been found.
  342. @c skip_limbo() {
  343.   while(1) {
  344.     if (loc>limit && get_line()==0) return;
  345.     *(limit+1)='@@';
  346.     while (*loc!='@@') loc++; /* look for '@@', then skip two chars */
  347.     if (loc++ <=limit) if (ccode[*loc++]==new_module) return;
  348. @ The |skip_TeX| routine is used on the first pass to skip through
  349. the \TeX\ code at the beginning of a module. It returns the next
  350. control code or `\.{\v}' found in the input. A |new_module| is
  351. assumed to exist at the very end of the file.
  352. @c unsigned skip_TeX() /* skip past pure \TeX\ code */
  353.   while (1) {
  354.     if (loc>limit && get_line()==0) return(new_module);
  355.     *(limit+1)='@@';
  356.     while (*loc!='@@' && *loc!='|') loc++;
  357.     if (*loc++ =='|') return('|');
  358.     if (loc<=limit) return(ccode[*(loc++)]);
  359. @* Inputting the next token.
  360. As stated above, \.{WEAVE}'s most interesting lexical scanning routine is the
  361. |get_next| function that inputs the next token of \cee\ input. However,
  362. |get_next| is not especially complicated.
  363. The result of |get_next| is either an ASCII code for some special character,
  364. or it is a special code representing a pair of characters (e.g., `\.{!=}'),
  365. or it is the numeric value computed by the |ccode|
  366. table, or it is one of the following special codes:
  367. \yskip\hang |identifier|: In this case the global variables |id_first| and
  368. |id_loc| will have been set to the beginning and ending-plus-one locations
  369. in the buffer, as required by the |id_lookup| routine.
  370. \yskip\hang |string|: The string will have been copied into the array
  371. |mod_text|; |id_first| and |id_loc| are set as above (now they are
  372. pointers into |mod_text|).
  373. \yskip\hang |constant|: The constant is copied into |mod_text|, with
  374. slight modifications; |id_first| and |id_loc| are set.
  375. \yskip\noindent Furthermore, some of the control codes cause
  376. |get_next| to take additional actions:
  377. \yskip\hang |xref_roman|, |xref_wildcard|, |xref_typewriter|, |TeX_string|,
  378. |verbatim|: The values of |id_first| and |id_loc| will have been set to
  379. the beginning and ending-plus-one locations in the buffer.
  380. \yskip\hang |module_name|: In this case the global variable |cur_module| will
  381. point to the |byte_start| entry for the module name that has just been scanned.
  382. \yskip\noindent If |get_next| sees `\.{@@!}'
  383. it sets |xref_switch| to |def_flag| and goes on to the next token.
  384. \yskip\noindent If |get_next| sees `\.{@@\$}'
  385. it sets |math_flag| to |!math_flag| and goes on to the next token.
  386. @d constant 0200 /* \cee\ string or \.{WEB} precomputed string */
  387. @d string 0201 /* \cee\ string or \.{WEB} precomputed string */
  388. @d identifier 0202 /* \cee\ identifier or reserved word */
  389. @<Global...@>=
  390. name_pointer cur_module; /* name of module just scanned */
  391. int math_flag;
  392. @ @<Include...@>=
  393. #include "ctype.h"
  394. @ As one might expect, |get_next| consists mostly of a big switch
  395. that branches to the various special cases that can arise.
  396. @c eight_bits get_next() /* produces the next input token */
  397.   eight_bits c; /* the current character */
  398.   while (1) {
  399.     @<Check if we're at the end of a preprocessor command@>;
  400.     if (loc>limit && get_line()==0) return(new_module);
  401.     c=*(loc++);
  402.     if (isdigit(c) || c=='\\' || c=='.') @<Get a constant@>@;
  403.     else if (isalpha(c) || c=='_') @<Get an identifier@>@;
  404.     else if (c=='\'' || c=='"' || (c=='<' && sharp_include_line==1)) @<Get a string@>@;
  405.     else if (c=='@@') @<Get control code and possible module name@>@;
  406.     else if (c==' ' || c==tab_mark) continue; /* ignore spaces and tabs */
  407.     if (c=='#' && loc==buffer+1) @<Raise preprocessor flag@>;
  408.     mistake: @<Compress two-symbol operator@>@;
  409.     return(c);
  410. @ Because preprocessor commands do not fit in with the rest of the syntax of C,
  411. we have to deal with them separately.  One solution is to enclose such
  412. commands between special markers.  Thus, when a \.\# is seen as the
  413. first character of a line, |get_next| returns a special code
  414. \\{left\_preproc} and raises a flag |preproc|.
  415. @d left_preproc 0207 /* begins a preprocessor command */
  416. @d right_preproc 0217 /* ends a preprocessor command */
  417. @<Glob...@>=
  418. boolean preprocessing=0; /* are we scanning a preprocessor command? */
  419. @ @<Raise prep...@>= {
  420.   preprocessing=1;
  421.   @<Check if next token is |include|@>;
  422.   return (left_preproc);
  423. @ An additional complication is the freakish use of \.< and \.> to delimit
  424. a file name in lines that start with |#include|.  We must treat this file
  425. name as a string.
  426. @<Glob...@>=
  427. boolean sharp_include_line=0; /* are we scanning a |#include| line? */
  428. @ @<Check if next token is |include|@>=
  429. while (*loc==' ' || *loc=='\t') loc++;
  430. if (strncmp(loc,"include",7)==0) sharp_include_line=1;
  431. @ When we get to the end of a preprocessor line,
  432. we lower the flag and send a code \\{right\_preproc}, unless
  433. the last character was a \.\\. 
  434. @<Check if we're at...@>=
  435.   while (loc==limit-1 && preprocessing && *loc=='\\')
  436.     if (get_line()==0) return(new_module); /* still in preprocessor mode */
  437.   if (loc>=limit && preprocessing) {
  438.     preprocessing=sharp_include_line=0;
  439.     return(right_preproc);
  440. @ The following code assigns values to the combinations \.{++},
  441. \.{--}, \.{->}, \.{>=}, \.{<=}, \.{==}, \.{<<}, \.{>>}, \.{!=}, \.{||} and
  442. \.{\&\&}.  The compound assignment operators (e.g., \.{+=}) are 
  443. separate tokens, according to the
  444. \def\ceeref{{\sl C Reference Manual}}%
  445. \ceeref.
  446. @d compress(c) if (loc++<=limit) return(c)
  447. @<Compress tw...@>=
  448. switch(c) {
  449.   case '/': if (*loc=='*') compress(begin_comment); break;
  450.   case '+': if (*loc=='+') compress(plus_plus); break;
  451.   case '-': if (*loc=='-') {compress(minus_minus);}
  452.     else if (*loc=='>') compress(minus_gt); break;
  453.   case '=': if (*loc=='=') compress(eq_eq); break;
  454.   case '>': if (*loc=='=') {compress(gt_eq);}
  455.     else if (*loc=='>') compress(gt_gt); break;
  456.   case '<': if (*loc=='=') {compress(lt_eq);}
  457.     else if (*loc=='<') compress(lt_lt); break;
  458.   case '&': if (*loc=='&') compress(and_and); break;
  459.   case '|': if (*loc=='|') compress(or_or); break;
  460.   case '!': if (*loc=='=') compress(not_eq); break;
  461. @ @<Get an identifier@>= {
  462.   id_first=--loc;
  463.   while (isalpha(*++loc) || isdigit(*loc) || *loc=='_');
  464.   id_loc=loc; return(identifier);
  465. @ Different conventions are followed by \TeX\ and \cee\ to express octal
  466. and hexadecimal numbers; it is reasonable to stick to each convention
  467. within its realm.  Thus the \cee\ part of a \.{WEB} file has octals
  468. introduced by \.0 and hexadecimals by \.{0x}, but \.{WEAVE} will print
  469. in italics or typewriter font, respectively, and introduced by single
  470. or double quotes.  In order to simplify the \TeX\ macro used to print 
  471. such constants, we replace some of the characters.
  472. Notice that in this section and the next, |id_first| and |id_loc|
  473. are pointers into the array |mod_text|, not into |buffer|.
  474. @<Get a constant@>= {
  475.   id_first=id_loc=mod_text+1;
  476.   if (*(loc-1)=='\\') {*id_loc++='~';
  477.   while (isdigit(*loc)) *id_loc++=*loc++;} /* octal constant */
  478.   else if (*(loc-1)=='0') {
  479.     if (*loc=='x' || *loc=='X') {*id_loc++='^'; loc++;
  480.       while (isxdigit(*loc)) *id_loc++=*loc++;} /* hex constant */
  481.     else if (isdigit(*loc)) {*id_loc++='~';
  482.       while (isdigit(*loc)) *id_loc++=*loc++;} /* octal constant */
  483.     else goto dec; /* decimal constant */
  484.   else { /* decimal constant */
  485.     if (*(loc-1)=='.' && !isdigit(*loc)) goto mistake; /* not a constant */
  486.     dec: *id_loc++=*(loc-1);
  487.     while (isdigit(*loc) || *loc=='.') *id_loc++=*loc++;
  488.     if (*loc=='e' || *loc=='E') { /* float constant */
  489.       *id_loc++='_'; loc++;
  490.       if (*loc=='+' || *loc=='-') *id_loc++=*loc++;
  491.       while (isdigit(*loc)) *id_loc++=*loc++;
  492.     }
  493.   if (*loc=='l' || *loc=='L') {*id_loc++='$'; loc++;}
  494.   return(constant);
  495. @ \cee\ strings and character constants, delimited by double and single
  496. quotes, respectively, can contain newlines or instances of their own
  497. delimiters if they are protected by a backslash.  We follow this
  498. convention, but do not allow the string to be longer than |longest_name|.
  499. @<Get a string@>= {
  500.   ASCII delim = c; /* what started the string */
  501.   id_first = mod_text+1;
  502.   id_loc = mod_text;
  503.   if (delim=='\'' && *(loc-2)=='@@') {*++id_loc='@@'; *++id_loc='@@';}
  504.   *++id_loc=delim;
  505.   if (delim=='<') delim='>'; /* for file names in |#include| lines */
  506.   while (1) {
  507.     if (loc>=limit) {
  508.       if(*(limit-1)!='\\') {
  509.         err_print("! String didn't end"); loc=limit; break;
  510. @.String didn't end@>
  511.       }
  512.       if(get_line()==0) {
  513.         err_print("! Input ended in middle of string"); loc=buffer; break;
  514. @.Input ended in middle of string@>
  515.       }
  516.     }
  517.     if ((c=*loc++)==delim) {
  518.       if (++id_loc<=mod_text_end) *id_loc=c;
  519.       break;
  520.     }
  521.     if (c=='\\') if (loc>=limit) continue;
  522.       else if (++id_loc<=mod_text_end) {
  523.         *id_loc = '\\'; c=*loc++;
  524.       }
  525.     if (++id_loc<=mod_text_end) *id_loc=c;
  526.   if (id_loc>=mod_text_end) {
  527.     printf("\n! String too long: ");
  528. @.String too long@>
  529.     ASCII_write(mod_text+1,25);
  530.     printf("..."); mark_error;
  531.   id_loc++;
  532.   return(string);
  533. @ After an \.{@@} sign has been scanned, the next character tells us
  534. whether there is more work to do.
  535. @<Get control code and possible module name@>= {
  536.   c=*loc++;
  537.   switch(ccode[c]) {
  538.     case underline: xref_switch=def_flag; continue;
  539.     case switch_math_flag: math_flag=!math_flag; continue;
  540. #ifdef DEBUG
  541.     case trace: tracing=c-'0'; continue;
  542. #endif DEBUG
  543.     case xref_roman: case xref_wildcard: case xref_typewriter:
  544.     case TeX_string: @<Scan to the next \.{@@>}@>;
  545.     case module_name:
  546.       @<Scan the module name and make |cur_module| point to it@>;
  547.     case verbatim: @<Scan a verbatim string@>;
  548.     case ascii_constant: @<Get a string@>;
  549.     default: return(ccode[c]);
  550. @ The occurrence of a module name sets |xref_switch| to zero,
  551. because the module name might (for example) follow \&{int}.
  552. @<Scan the module name...@>= {
  553.   ASCII *k; /* pointer into |mod_text| */
  554.   @<Put module name into |mod_text|@>;
  555.   if (k-mod_text>3 && strncmp(k-2,"...",3)==0) cur_module=prefix_lookup(mod_text+1,k-3);
  556.   else cur_module=mod_lookup(mod_text+1,k);
  557.   xref_switch=0; return(module_name);
  558. @ Module names are placed into the |mod_text| array with consecutive spaces,
  559. tabs, and carriage-returns replaced by single spaces. There will be no
  560. spaces at the beginning or the end. (We set |mod_text[0]=' '| to facilitate
  561. this, since the |mod_lookup| routine uses |mod_text[1]| as the first
  562. character of the name.)
  563. @<Set init...@>=mod_text[0]=' ';
  564. @ @<Put module name...@>=
  565. k=mod_text;
  566. while (1) {
  567.   if (loc>limit && get_line()==0) {
  568.     err_print("! Input ended in section name");
  569. @.Input ended in section name@>
  570.     loc=buffer+1; break;
  571.   c=*loc;
  572.   @<If end of name, |break|@>;
  573.   loc++; if (k<mod_text_end) k++;
  574.   if (c==' ' || c==tab_mark) {
  575.     c=' '; if (*(k-1)==' ') k--;
  576. *k=c;
  577. if (k>=mod_text_end) {
  578.   printf("\n! Section name too long: ");
  579. @.Section name too long@>
  580.   ASCII_write(mod_text+1,25);
  581.   printf("..."); mark_harmless;
  582. if (*k==' ' && k>mod_text) k--;
  583. @ @<If end of name,...@>=
  584. if (c=='@@') {
  585.   c=*(loc+1);
  586.   if (c=='>') {
  587.     loc+=2; break;
  588.   if (ccode[c]==new_module) {
  589.     err_print("! Section name didn't end"); break;
  590. @.Section name didn't end@>
  591.   *(++k)='@@'; loc++; /* now |c==*loc| again */
  592. @ @<Scan to the next...@>= {
  593.   c=ccode[*(loc-1)]; id_first=loc; *(limit+1)='@@';
  594.   while (*loc!='@@') loc++;
  595.   id_loc=loc;
  596.   if (loc++>limit) {
  597.     err_print("! Control text didn't end"); loc=limit; return(c);
  598. @.Control text didn't end@>
  599.   if (*loc++!='>') err_print("! Control codes are forbidden in control text");
  600. @.Control codes are forbidden...@>
  601.   return(c);
  602. @ At the present point in the program we
  603. have |*(loc-1)=verbatim|; we set |id_first| to the beginning
  604. of the string itself, and |id_loc| to its ending-plus-one location in the
  605. buffer.  We also set |loc| to the position just after the ending delimiter.
  606. @<Scan a verbatim string@>= {
  607.   id_first=loc++; *(limit+1)='@@'; *(limit+2)='>';
  608.   while (*loc!='@@' || *(loc+1)!='>') loc++;
  609.   if (loc>=limit) err_print("! Verbatim string didn't end");
  610. @.Verbatim string didn't end@>
  611.   id_loc=loc; loc+=2;
  612.   return (verbatim);
  613. @* Phase one processing.
  614. We now have accumulated enough subroutines to make it possible to carry out
  615. \.{WEAVE}'s first pass over the source file. If everything works right,
  616. both phase one and phase two of \.{WEAVE} will assign the same numbers to
  617. modules, and these numbers will agree with what \.{TANGLE} does.
  618. The global variable |next_control| often contains the most recent output of
  619. |get_next|; in interesting cases, this will be the control code that
  620. ended a module or part of a module.
  621. @<Global...@>=
  622. eight_bits next_control; /* control code waiting to be acting upon */
  623. @ The overall processing strategy in phase one has the following
  624. straightforward outline.
  625. @c phase_one() {
  626. phase=1; reset_input(); module_count=0;
  627. skip_limbo(); change_exists=0;
  628. while (!input_has_ended)
  629.   @<Store cross-reference data for the current module@>;
  630. changed_module[module_count]=change_exists;
  631.   /* the index changes if anything does */
  632. phase=2; /* prepare for second phase */
  633. @<Print error messages about unused or undefined module names@>;
  634. @ @<Store cross-reference data...@>=
  635.   if (++module_count==max_modules) overflow("section number");
  636.   changed_module[module_count]=0; /* it will become 1 if any line changes */
  637.   if (*(loc-1)=='*') {
  638.     printf("*%d",module_count);
  639.     update_terminal; /* print a progress report */
  640.   @<Store cross-references in the \TeX\ part of a module@>;
  641.   @<Store cross-references in the definition part of a module@>;
  642.   @<Store cross-references in the \cee\ part of a module@>;
  643.   if (changed_module[module_count]) change_exists=1;
  644. @ The |C_xref| subroutine stores references to identifiers in
  645. \cee\ text material beginning with the current value of |next_control|
  646. and continuing until |next_control| is `\.\{' or `\.{\v}', or until the next
  647. ``milestone'' is passed (i.e., |next_control>=format|). If
  648. |next_control>=format| when |C_xref| is called, nothing will happen;
  649. but if |next_control="|"| upon entry, the procedure assumes that this is
  650. the `\.{\v}' preceding \cee\ text that is to be processed.
  651. The program uses the fact that our internal code numbers satisfy
  652. the relations |xref_roman=identifier+roman| and |xref_wildcard=identifier
  653. +wildcard| and |xref_typewriter=identifier+typewriter| and |normal=0|.
  654. @c C_xref() /* makes cross-references for \cee\ identifiers */
  655.   name_pointer p; /* a referenced name */
  656.   while (next_control<format) {
  657.     if (next_control>=identifier && next_control<=xref_typewriter) {
  658.       p=id_lookup(id_first, id_loc,next_control-identifier); new_xref(p);
  659.     }
  660.     next_control=get_next();
  661.     if (next_control=='|' || next_control==begin_comment) return;
  662. @ The |outer_xref| subroutine is like |C_xref| but it begins
  663. with |next_control!='|'| and ends with |next_control>=format|. Thus, it
  664. handles \cee\ text with embedded comments.
  665. @c outer_xref() /* extension of |C_xref| */
  666.   int bal; /* brace level in comment */
  667.   while (next_control<format)
  668.     if (next_control!=begin_comment) C_xref();
  669.     else {
  670.       bal=copy_comment(1); next_control='|';
  671.       while (bal>0) {
  672.     C_xref();
  673.     if (next_control=='|') bal=copy_comment(bal);
  674.     else bal=0; /* an error message will occur in phase two */
  675.       }
  676.     }
  677. @ In the \TeX\ part of a module, cross-reference entries are made only for
  678. the identifiers in \cee\ texts enclosed in \pb, or for control texts
  679. enclosed in \.{@@\^}$\,\ldots\,$\.{@@>} or \.{@@.}$\,\ldots\,$\.{@@>}
  680. or \.{@@:}$\,\ldots\,$\.{@@>}.
  681. @<Store cross-references in the \T...@>=
  682. while (1) {
  683.   switch (next_control=skip_TeX()) {
  684.     case underline: xref_switch=def_flag; continue;
  685. #ifdef DEBUG
  686.     case trace: tracing=next_control-'0'; continue;
  687. #endif DEBUG
  688.     case '|': C_xref(); break;
  689.     case xref_roman: case xref_wildcard: case xref_typewriter: case module_name:
  690.       loc-=2; next_control=get_next(); /* scan to \.{@@>} */
  691.       if (next_control!=module_name)
  692.         new_xref(id_lookup(id_first, id_loc,next_control-identifier));
  693.       break;
  694.   if (next_control>=format) break;
  695. @ During the definition and \cee\ parts of a module, cross-references
  696. are made for all identifiers except reserved words; however, the
  697. identifiers in a format definition are referenced even if they are
  698. reserved. The \TeX\ code in comments is, of course, ignored, except for
  699. \cee\ portions enclosed in \pb; the text of a module name is skipped
  700. entirely, even if it contains \pb\ constructions.
  701. The variables |lhs| and |rhs| point to the respective identifiers involved
  702. in a format definition.
  703. @<Global...@>=
  704. name_pointer lhs, rhs; /* pointers to |byte_start| for format identifiers */
  705. @ When we get to the following code we have |next_control>=format|.
  706. @<Store cross-references in the d...@>=
  707. while (next_control<=definition) { /* |format| or |definition| */
  708.   xref_switch=def_flag; /* implied \.{@@!} */
  709.   if (next_control==definition) next_control=get_next();
  710.   else @<Process a format definition@>;
  711.   outer_xref();
  712. @ Error messages for improper format definitions will be issued in phase
  713. two. Our job in phase one is to define the |ilk| of a properly formatted
  714. identifier, and to fool the |new_xref| routine into thinking that the
  715. identifier on the right-hand side of the format definition is not a
  716. reserved word.
  717. @<Process a form...@>= {
  718.   next_control=get_next();
  719.   if (next_control==identifier) {
  720.     lhs=id_lookup(id_first, id_loc,normal); lhs->ilk=normal; new_xref(lhs);
  721.     next_control=get_next();
  722.     if (next_control==identifier) {
  723.       rhs=id_lookup(id_first, id_loc,normal);
  724.       lhs->ilk=rhs->ilk; rhs->ilk=normal; new_xref(rhs);
  725.       rhs->ilk=lhs->ilk; next_control=get_next();
  726.     }
  727. @ Finally, when the \TeX\ and definition parts have been treated, we have
  728. |next_control>=begin_C|.
  729. @<Store cross-references in the \cee...@>=
  730. if (next_control<=module_name) {  /* |begin_C| or |module_name| */
  731.   if (next_control==begin_C) mod_xref_switch=0;
  732.   else mod_xref_switch=def_flag;
  733.   do {
  734.     if (next_control==module_name && cur_module!=NULL) new_mod_xref(cur_module);
  735.     next_control=get_next(); outer_xref();
  736.   } while ( next_control<=module_name);
  737. @ After phase one has looked at everything, we want to check that each
  738. module name was both defined and used.  The variable |cur_xref| will point
  739. to cross-references for the current module name of interest.
  740. @<Global...@>=
  741. xref_pointer cur_xref; /* temporary cross-reference pointer */
  742. @ The following recursive procedure
  743. walks through the tree of module names and prints out anomalies.
  744. @^recursion@>
  745. @c mod_check(p) name_pointer p; /* print anomalies in subtree |p| */
  746.   if (p) {
  747.     mod_check(p->llink);
  748.     cur_xref=(xref_pointer)p->xref;
  749.     if (cur_xref->num <def_flag) {
  750.       printf("\n! Never defined: <"); print_id(p); putchar('>'); mark_harmless;
  751. @.Never defined: <section name>@>
  752.     }
  753.     while (cur_xref->num >=def_flag) cur_xref=cur_xref->xlink;
  754.     if (cur_xref==xmem) {
  755.       printf("\n! Never used: <"); print_id(p); putchar('>'); mark_harmless;
  756. @.Never used: <section name>@>
  757.     }
  758.     mod_check(p->rlink);
  759. @ @<Print error messages about un...@>=mod_check(root)
  760. @* Low-level output routines.
  761. The \TeX\ output is supposed to appear in lines at most |line_length|
  762. characters long, so we place it into an output buffer. During the output
  763. process, |out_line| will hold the current line number of the line about to
  764. be output.
  765. @<Global...@>=
  766. ASCII out_buf[line_length+1]; /* assembled characters */
  767. ASCII *out_ptr; /* just after last character in |out_buf| */
  768. ASCII *out_buf_end = out_buf+line_length; /* end of |out_buf| */
  769. int out_line; /* number of next line to be output */
  770. @ The |flush_buffer| routine empties the buffer up to a given breakpoint,
  771. and moves any remaining characters to the beginning of the next line.
  772. If the |per_cent| parameter is 1 a |'%'| is appended to the line
  773. that is being output; in this case the breakpoint |b| should be strictly
  774. less than |out_buf_end|. If the |per_cent| parameter is |0|,
  775. trailing blanks are suppressed.
  776. The characters emptied from the buffer form a new line of output.
  777. The same caveat that applies to |ASCII_write| applies to |c_line_write|.
  778. @d c_line_write(c) fflush(tex_file),write(fileno(tex_file),out_buf+1,c)
  779. @d tex_putxchar(c) putc(xchr[c],tex_file)
  780. @d tex_new_line putc('\n',tex_file)
  781. @d tex_printf(c) fprintf(tex_file,c)
  782. @c flush_buffer(b,per_cent)
  783. ASCII *b;
  784. boolean per_cent; /* outputs from |out_buf+1| to |b|,where |b<=out_ptr| */
  785.   ASCII *j; j=b; /* pointer into |out_buffer| */
  786.   if (! per_cent) /* remove trailing blanks */
  787.     while (j>out_buf && *j==' ') j--;
  788.   c_line_write(j-out_buf);
  789.   if (per_cent) tex_putxchar('%');
  790.   tex_new_line; out_line++;
  791.   if (b<out_ptr) strncpy(out_buf+1,b+1,out_ptr-b);
  792.   out_ptr-=b-out_buf;
  793. @ When we are copying \TeX\ source material, we retain line breaks
  794. that occur in the input, except that an empty line is not
  795. output when the \TeX\ source line was nonempty. For example, a line
  796. of the \TeX\ file that contains only an index cross-reference entry
  797. will not be copied. The |finish_line| routine is called just before
  798. |get_line| inputs a new line, and just after a line break token has
  799. been emitted during the output of translated \cee\ text.
  800. @c finish_line() /* do this at the end of a line */
  801.   ASCII *k; /* pointer into |buffer| */
  802.   if (out_ptr>out_buf) flush_buffer(out_ptr,0);
  803.   else {
  804.     for (k=buffer; k<=limit; k++)
  805.       if (*k!=' ' && *k!=tab_mark) return;
  806.     flush_buffer(out_buf,0);
  807. @ In particular, the |finish_line| procedure is called near the very
  808. beginning of phase two. We initialize the output variables in a slightly
  809. tricky way so that the first line of the output file will be
  810. `\.{\\input cwebmac}'.
  811. @<Set init...@>=
  812. out_ptr=out_buf+1; out_line=1; *out_ptr='c'; tex_printf("\\input cwebma");
  813. @ When we wish to append one character |c| to the output buffer, we write
  814. `|out(c)|'; this will cause the buffer to be emptied if it was already
  815. full.  If we want to append more than one character at once, we say
  816. |out_str(s)|, where |s| is a string containing the characters,
  817. or |out_str_del(s,t)|, where |s| and |t| point to the same array of
  818. characters; characters from |s| to |t-1|, inclusive, are output.
  819. A line break will occur at a space or after a single-nonletter
  820. \TeX\ control sequence.
  821. @d out(c) {if (out_ptr>=out_buf_end) break_out(); *(++out_ptr)=c;}
  822. @c out_str_del(s,t) /* output characters from |s| to |t-1| */
  823. ASCII *s, *t;
  824.   while (s<t) out(*s++);
  825. out_str(s) /* output characters from |s| to end of string */
  826. ASCII *s;
  827.   while (*s) out(*s++);
  828. @ The |break_out| routine is called just before the output buffer is about
  829. to overflow. To make this routine a little faster, we initialize position
  830. 0 of the output buffer to `\.\\'; this character isn't really output.
  831. @<Set init...@>=
  832. out_buf[0]='\\';
  833. @ A long line is broken at a blank space or just before a backslash that isn't
  834. preceded by another backslash. In the latter case, a |'%'| is output at
  835. the break.
  836. @c break_out() /* finds a way to break the output line */
  837.   ASCII *k=out_ptr; /* pointer into |out_buf| */
  838.   while (1) {
  839.     if (k==out_buf) @<Print warning message, break the line, |return|@>;
  840.     if (*k==' ') {
  841.       flush_buffer(k,0); return;
  842.     }
  843.     if (*(k--)=='\\' && *k!='\\') { /* we've decreased |k| */
  844.       flush_buffer(k,1); return;
  845.     }
  846. @ We get to this module only in the unusual case that the entire output line
  847. consists of a string of backslashes followed by a string of nonblank
  848. non-backslashes. In such cases it is almost always safe to break the
  849. line by putting a |'%'| just before the last character.
  850. @<Print warning message...@>=
  851.   printf("\n! Line had to be broken (output l. %d):\n",out_line);
  852. @.Line had to be broken@>
  853.   ASCII_write(out_buf+1, out_ptr-out_buf-1);
  854.   new_line; mark_harmless;
  855.   flush_buffer(out_ptr-1,1); return;
  856. @ Here is a macro that outputs a module number in decimal notation.
  857. The number to be converted by |out_mod| is known to be less than
  858. |def_flag|, so it cannot have more than five decimal digits.  If
  859. the module is changed, we output `\.{\\*}' just after the number.
  860. @c out_mod(n) sixteen_bits n;
  861.   ASCII s[6];
  862.   sprintf(s,"%d",n); out_str(s);
  863.   if(changed_module[n]) out_str ("\\*");
  864. @ The |out_name| procedure is used to output an identifier or index
  865. entry, enclosing it in braces.
  866. @c out_name(p) name_pointer p; {
  867.   ASCII *k, *k_end=(p+1)->byte_start; /* pointers into |byte_mem| */
  868.   out('{');
  869.   for (k=p->byte_start; k<k_end; k++) {
  870.     if (*k=='_') out('\\');
  871.     out(*k);
  872.   out('}');
  873. @* Routines that copy \TeX\ material.
  874. During phase two, we use the subroutines |copy_limbo|, |copy_TeX|, and
  875. |copy_comment| in place of the analogous |skip_limbo|, |skip_TeX|, and
  876. |skip_comment| that were used in phase one.
  877. The |copy_limbo| routine, for example, takes \TeX\ material that is not
  878. part of any module and transcribes it almost verbatim to the output file.
  879. No `\.{@@}' signs should occur in such material except in `\.{@@@@}'
  880. pairs; such pairs are replaced by singletons.
  881. @c copy_limbo()
  882.   ASCII c;
  883.   while (1) {
  884.     if (loc>limit && (finish_line(), get_line()==0)) return;
  885.     *(limit+1)='@@';
  886.     while (*loc!='@@') out(*(loc++));
  887.     if (loc++<=limit) {
  888.       c=*loc++;
  889.       if (ccode[c]==new_module) break;
  890.       if (c!='z' && c!='Z') {
  891.         out('@@');
  892.         if (c!='@@') err_print("! Double @@ required outside of sections");
  893. @.Double {\AT} required...@>
  894.       }
  895.     }
  896. @ The |copy_TeX| routine processes the \TeX\ code at the beginning of a
  897. module; for example, the words you are now reading were copied in this
  898. way. It returns the next control code or `\.{\v}' found in the input.
  899. We don't copy spaces or tab marks into the beginning of a line. This
  900. makes the test for empty lines in |finish_line| work.
  901. @<Global...@>= eight_bits next_control; /* control code found */
  902. @ @c eight_bits copy_TeX()
  903.   ASCII c; /* current character being copied */
  904.   while (1) {
  905.     if (loc>limit && (finish_line(), get_line()==0)) return(new_module);
  906.     *(limit+1)='@@';
  907.     while ((c=*(loc++))!='|' && c!='@@') {
  908.       out(c);
  909.       if (out_ptr==out_buf+1 && (c==' ' || c==tab_mark)) out_ptr--;
  910.     }
  911.     if (c=='|') return('|');
  912.     if (loc<=limit) return(ccode[*(loc++)]);
  913. @ The |copy_comment| function issues a warning if more braces are opened than
  914. closed, and in the case of a more serious error it supplies enough
  915. braces to keep \TeX\ from complaining about unbalanced braces.
  916. Instead of copying the \TeX\ material
  917. into the output buffer, this function copies it into the token memory.
  918. The abbreviation |app_tok(t)| is used to append token |t| to the current
  919. token list, and it also makes sure that it is possible to append at least
  920. one further token without overflow.
  921. @d app_tok(c) {if (tok_ptr+2>tok_mem_end) overflow("token"); *(tok_ptr++)=c;}
  922. @c copy_comment(bal) /* copies \TeX\ code in comments */
  923. int bal; /* brace balance */
  924.   ASCII c; /* current character being copied */
  925.   while (1) {
  926.     if (loc>limit) if (get_line()==0) {
  927.         err_print("! Input ended in mid-comment");
  928. @.Input ended in mid-comment@>
  929.         loc=buffer+1; @<Clear |bal| and |return|@>;
  930.       }
  931.     c=*(loc++);
  932.     if (c=='|') return(bal);
  933.     @<Check for end of comment@>;
  934.     if (phase==2) app_tok(c);
  935.     @<Copy special things when |c=='@@', '\\'|; |return| at end@>;
  936. @ @<Check for end of comment@>=
  937. if (c=='*' && *loc=='/') {
  938.   loc++; if(bal==1) {if (phase==2) app_tok('}'); return(0);}
  939.   else {
  940.     err_print("! Braces don't balance in comment");
  941. @.Braces don't balance in comment@>
  942.     @<Clear |bal| and |return|@>;
  943. @ @<Copy special things when |c=='@@'...@>=
  944. if (c=='@@') {
  945.   if (*(loc++)!='@@') {
  946.     err_print("! Illegal use of @@ in comment");
  947. @.Illegal use of {\AT}...@>
  948.     loc-=2; if (phase==2) tok_ptr--; @<Clear |bal|...@>;
  949. else if (c=='\\' && *loc!='@@' && phase==2) app_tok(*(loc++))
  950. @ When the comment has terminated abruptly due to an error, we output
  951. enough right braces to keep \TeX\ happy.
  952. @<Clear |bal|...@>=
  953. app_tok(' '); /* this is done in case the previous character was `\.\\' */
  954. while (bal-- >0) app_tok('}');
  955. return(0);
  956. @* Parsing.
  957. The most intricate part of \.{WEAVE} is its mechanism for converting
  958. \cee-like code into \TeX\ code, and we might as well plunge into this
  959. aspect of the program now. A ``bottom up'' approach is used to parse the
  960. \cee-like material, since \.{WEAVE} must deal with fragmentary
  961. constructions whose overall ``part of speech'' is not known.
  962. At the lowest level, the input is represented as a sequence of entities
  963. that we shall call {\it scraps}, where each scrap of information consists
  964. of two parts, its {\it category} and its {\it translation}. The category
  965. is essentially a syntactic class, and the translation is a token list that
  966. represents \TeX\ code. Rules of syntax and semantics tell us how to
  967. combine adjacent scraps into larger ones, and if we are lucky an entire
  968. \cee\ text that starts out as hundreds of small scraps will join
  969. together into one gigantic scrap whose translation is the desired \TeX\
  970. code. If we are unlucky, we will be left with several scraps that don't
  971. combine; their translations will simply be output, one by one.
  972. The combination rules are given as context-sensitive productions that are
  973. applied from left to right. Suppose that we are currently working on the
  974. sequence of scraps $s_1\,s_2\ldots s_n$. We try first to find the longest
  975. production that applies to an initial substring $s_1\,s_2\ldots\,$; but if
  976. no such productions exist, we find to find the longest production
  977. applicable to the next substring $s_2\,s_3\ldots\,$; and if that fails, we
  978. try to match $s_3\,s_4\ldots\,$, etc.
  979. A production applies if the category codes have a given pattern. For
  980. example, one of the productions is
  981. $$\hbox{|exp| |binop| |exp| $\RA$ |exp|}$$
  982. and it means that three consecutive scraps whose respective categories are
  983. |exp|, |binop|, and |exp| are con\-verted to one scraps whose category
  984. is |exp|.  The scraps are simply concatenated.  The case of
  985. $$\hbox{|exp| |comma| |exp| $\RA$ |exp|}$$
  986. is only slightly more complicated: here the resulting |exp| scrap
  987. consists not only of the three original scraps, but also of the
  988. tokens |opt| and 9 before the |comma| and the following |exp|.
  989. In the \TeX\ file,
  990. this will specify an additional thin space after the comma, followed
  991. by an optional line break with penalty 90.
  992. At each opportunity the longest possible production is applied:
  993. for example, if the current sequence of scraps is |struct_like|
  994. |exp| |lbrace| this is transformed into a |struct_head| by rule
  995. 31, but if the sequence is 
  996. |struct_like| |exp| followed by anything other than |lbrace| only
  997. two scraps are used (by rule 32) to form an |int_like|.
  998. Translation rules use subscripts
  999. to distinguish between translations of scraps whose categories have the
  1000. same initial letter; these subscripts are assigned from left to right.
  1001. @ Here is a list of the category codes that scraps can have.
  1002. @d exp 1 /* denotes an expression, including perhaps a single identifier */
  1003. @d unop 2 /* denotes a unary operator */
  1004. @d binop 3 /* denotes a binary operator */
  1005. @d unorbinop 4
  1006.   /* denotes an operator that can be unary or binary, depending on context */
  1007. @d cast 5 /* denotes a cast */
  1008. @d question 6 /* denotes a question mark and possibly the expressions flanking it */
  1009. @d lbrace 7 /* denotes a left brace */
  1010. @d rbrace 8 /* denotes a right brace */
  1011. @d decl_head 9 /* denotes an incomplete declaration */
  1012. @d comma 10 /* denotes a comma */
  1013. @d lpar 11 /* denotes a left parenthesis or left bracket */
  1014. @d rpar 12 /* denotes a right parenthesis or right bracket */
  1015. @d max_math 19 /* category codes below this can only be printed in math mode */
  1016. @d struct_head 21 /* denotes the beginning of a structure specifier */
  1017. @d decl 20 /* denotes a complete declaration */
  1018. @d stmt 23 /* denotes a complete statement */
  1019. @d function 24 /* denotes a complete function */
  1020. @d fn_decl 25 /* denotes a function declarator */
  1021. @d else_like 26 /* denotes the beginning of a conditional */
  1022. @d if_head 30 /* denotes the beginning of a conditional */
  1023. @d semi 27 /* denotes a semicolon */
  1024. @d colon 28 /* denotes a colon */
  1025. @d tag 29 /* denotes a statement label */
  1026. @d lproc 35 /* begins a preprocessor command */
  1027. @d rproc 36 /* ends a preprocessor command */
  1028. @d ignore_scrap 37 /* a full preprocessor command */
  1029. @<Glo...@>=
  1030. char cat_name[256][12];
  1031. eight_bits cat_index;
  1032. @ @<Set in...@>=
  1033.     for (cat_index=0;cat_index<255;cat_index++)
  1034.       strcpy(cat_name[cat_index],"UNKNOWN");
  1035.     strcpy(cat_name[exp],"exp");
  1036.     strcpy(cat_name[stmt],"stmt");
  1037.     strcpy(cat_name[decl],"decl");
  1038.     strcpy(cat_name[decl_head],"decl_head");
  1039.     strcpy(cat_name[struct_head],"struct_head");
  1040.     strcpy(cat_name[function],"function");
  1041.     strcpy(cat_name[fn_decl],"fn_decl");
  1042.     strcpy(cat_name[else_like],"else_like");
  1043.     strcpy(cat_name[if_head],"if_head");
  1044.     strcpy(cat_name[unop],"unop");
  1045.     strcpy(cat_name[binop],"binop");
  1046.     strcpy(cat_name[unorbinop],"unorbinop");
  1047.     strcpy(cat_name[semi],";");
  1048.     strcpy(cat_name[colon],":");
  1049.     strcpy(cat_name[comma],",");
  1050.     strcpy(cat_name[question],"?");
  1051.     strcpy(cat_name[tag],"tag");
  1052.     strcpy(cat_name[cast],"cast");
  1053.     strcpy(cat_name[lpar],"(");
  1054.     strcpy(cat_name[rpar],")");
  1055.     strcpy(cat_name[lbrace],"{");
  1056.     strcpy(cat_name[rbrace],"}");
  1057.     strcpy(cat_name[lproc],"#{");
  1058.     strcpy(cat_name[rproc],"#}");
  1059.     strcpy(cat_name[ignore_scrap],"ignore");
  1060.     strcpy(cat_name[define_like],"define");
  1061.     strcpy(cat_name[do_like],"do");
  1062.     strcpy(cat_name[if_like],"if");
  1063.     strcpy(cat_name[int_like],"int");
  1064.     strcpy(cat_name[parms_like],"parms");
  1065.     strcpy(cat_name[case_like],"case");
  1066.     strcpy(cat_name[sizeof_like],"sizeof");
  1067.     strcpy(cat_name[struct_like],"struct");
  1068.     strcpy(cat_name[typedef_like],"typedef");
  1069.     strcpy(cat_name[0],"zero");
  1070. #ifdef DEBUG
  1071. print_cat(c) /* symbolic printout of a category */
  1072. eight_bits c;
  1073.   printf(cat_name[c]);
  1074. #endif DEBUG
  1075. @ The token lists for translated \TeX\ output contain some special control
  1076. symbols as well as ordinary characters. These control symbols are
  1077. interpreted by \.{WEAVE} before they are written to the output file.
  1078. \yskip\hang |break_space| denotes an optional line break or an en space;
  1079. \yskip\hang |force| denotes a line break;
  1080. \yskip\hang |big_force| denotes a line break with additional vertical space;
  1081. \yskip\hang |preproc_line| denotes that the line will be printed flush left;
  1082. \yskip\hang |opt| denotes an optional line break (with the continuation
  1083. line indented two ems with respect to the normal starting position)---this
  1084. code is followed by an integer |n|, and the break will occur with penalty
  1085. $10n$;
  1086. \yskip\hang |backup| denotes a backspace of one em;
  1087. \yskip\hang |cancel| obliterates any |break_space| or |force| or |big_force|
  1088. tokens that immediately precede or follow it and also cancels any
  1089. |backup| tokens that follow it;
  1090. \yskip\hang |indent| causes future lines to be indented one more em;
  1091. \yskip\hang |outdent| causes future lines to be indented one less em.
  1092. \yskip\noindent All of these tokens are removed from the \TeX\ output that
  1093. comes from \cee\ text between \pb\ signs; |break_space| and |force| and
  1094. |big_force| become single spaces in this mode. The translation of other
  1095. \cee\ texts results in \TeX\ control sequences \.{\\1}, \.{\\2},
  1096. \.{\\3}, \.{\\4}, \.{\\5}, \.{\\6}, \.{\\7}, \.{\\8}
  1097. corresponding respectively to
  1098. |indent|, |outdent|, |opt|, |backup|, |break_space|, |force|,
  1099. |big_force| and |preproc_line|.
  1100. However, a sequence of consecutive `\.\ ', |break_space|,
  1101. |force|, and/or |big_force| tokens is first replaced by a single token
  1102. (the maximum of the given ones).
  1103. The tokens |math_rel| and |math_bin| will be translated into
  1104. \.{\\mathrel\{} and \.{\\mathbin\{}, respectively.
  1105. Other control sequences in the \TeX\ output will be `\.{\\\\\{}$\,\ldots\,$\.\}'
  1106. surrounding identifiers, `\.{\\\&\{}$\,\ldots\,$\.\}' surrounding
  1107. reserved words, `\.{\\.\{}$\,\ldots\,$\.\}' surrounding strings,
  1108. `\.{\\cee\{}$\,\ldots\,$\.\}$\,$|force|' surrounding comments, and
  1109. `\.{\\X$n$:}$\,\ldots\,$\.{\\X}' surrounding module names, where
  1110. |n| is the module number.
  1111. @d math_bin 0205
  1112. @d math_rel 0206
  1113. @d big_cancel 0210 /* like |cancel|, also overrides spaces */
  1114. @d cancel 0211 /* overrides |backup|, |break_space|, |force|, |big_force| */
  1115. @d indent 0212 /* one more tab (\.{\\1}) */
  1116. @d outdent 0213 /* one less tab (\.{\\2}) */
  1117. @d opt 0214 /* optional break in mid-statement (\.{\\3}) */
  1118. @d backup 0215 /* stick out one unit to the left (\.{\\4}) */
  1119. @d break_space 0216 /* optional break between statements (\.{\\5}) */
  1120. @d force 0217 /* forced break between statements (\.{\\6}) */
  1121. @d big_force 0220 /* forced break with additional space (\.{\\7}) */
  1122. @d preproc_line 0221 /* forced break with additional space (\.{\\8}) */
  1123. @d end_translation 0222 /* special sentinel token at end of list */
  1124. @i examples/prod.web
  1125. @* Implementing the productions.
  1126. More specifically, a scrap is a structure consisting of a category
  1127. |cat| and a |text_pointer| |trans|, which points to the translation in
  1128. |tok_start|.  When \cee\ text is to be processed with the grammar above,
  1129. we form an array |scrap_info| containing the initial scraps.
  1130. Our production rules have the nice property that the right-hand side is never
  1131. longer than the left-hand side. Therefore it is convenient to use sequential
  1132. allocation for the current sequence of scraps. Five pointers are used to
  1133. manage the parsing:
  1134. \yskip\hang |pp| is a pointer into |scrap_info|.  We will try to match
  1135. the category codes |pp->cat@,(pp+1)->cat|$\,\ldots\,$ to the left-hand sides
  1136. of productions.
  1137. \yskip\hang |scrap_base|, |lo_ptr|, |hi_ptr|, and |scrap_ptr| are such that
  1138. the current sequence of scraps appears in positions |scrap_base| through
  1139. |lo_ptr| and |hi_ptr| through |scrap_ptr|, inclusive, in the |cat| and
  1140. |trans| arrays. Scraps located between |scrap_base| and |lo_ptr| have
  1141. been examined, while those in positions |>=hi_ptr| have not yet been
  1142. looked at by the parsing process.
  1143. \yskip\noindent Initially |scrap_ptr| is set to the position of the final
  1144. scrap to be parsed, and it doesn't change its value. The parsing process
  1145. makes sure that |lo_ptr>=pp+3|, since productions have as many as four terms,
  1146. by moving scraps from |hi_ptr| to |lo_ptr|. If there are
  1147. fewer than |pp+3| scraps left, the positions up to |pp+3| are filled with
  1148. blanks that will not match in any productions. Parsing stops when
  1149. |pp=lo_ptr+1| and |hi_ptr=scrap_ptr+1|.
  1150. Since the |scrap| structure will later be used for other purposes, we
  1151. declare its second element as unions.
  1152. @<Type...@>=
  1153. typedef struct {
  1154.   eight_bits cat;
  1155.   eight_bits mathness;
  1156.   union {
  1157.     text_pointer Trans;
  1158.     @<Rest of |trans_plus| union@>@;
  1159.   } trans_plus;
  1160. } scrap;
  1161. typedef scrap *scrap_pointer;
  1162. @ @d trans trans_plus.Trans /* translation texts of scraps */
  1163. @d no_math 2
  1164. @d yes_math 1
  1165. @d maybe_math 0
  1166. @<Global...@>=
  1167. scrap scrap_info[max_scraps]; /* memory array for scraps */
  1168. scrap_pointer scrap_info_end=scrap_info+max_scraps -1; /* end of |scrap_info| */
  1169. scrap_pointer pp; /* current position for reducing productions */
  1170. scrap_pointer scrap_base; /* beginning of the current scrap sequence */
  1171. scrap_pointer scrap_ptr; /* ending of the current scrap sequence */
  1172. scrap_pointer lo_ptr; /* last scrap that has been examined */
  1173. scrap_pointer hi_ptr; /* first scrap that has not been examined */
  1174. #ifdef STAT
  1175. scrap_pointer max_scr_ptr; /* largest value assumed by |scrap_ptr| */
  1176. #endif STAT
  1177. @ @<Set init...@>=
  1178. scrap_base=scrap_info+1;
  1179. #ifdef STAT
  1180. max_scr_ptr=
  1181. #endif STAT
  1182. scrap_ptr=scrap_info;
  1183. @ Token lists in |@!tok_mem| are composed of the following kinds of
  1184. items for \TeX\ output.
  1185. \yskip\item{$\bullet$}ASCII codes and special codes like |force| and
  1186. |math_rel| represent themselves;
  1187. \item{$\bullet$}|id_flag+p| represents \.{\\\\\{{\rm identifier $p$}\}};
  1188. \item{$\bullet$}|res_flag+p| represents \.{\\\&\{{\rm identifier $p$}\}};
  1189. \item{$\bullet$}|mod_flag+p| represents module name |p|;
  1190. \item{$\bullet$}|tok_flag+p| represents token list number |p|;
  1191. \item{$\bullet$}|inner_tok_flag+p| represents token list number |p|, to be
  1192. translated without line-break controls.
  1193. @d id_flag 10240 /* signifies an identifier */
  1194. @d res_flag 2*id_flag /* signifies a reserved word */
  1195. @d mod_flag 3*id_flag /* signifies a module name */
  1196. @d tok_flag 4*id_flag /* signifies a token list */
  1197. @d inner_tok_flag 5*id_flag /* signifies a token list in `\pb' */
  1198. #ifdef DEBUG
  1199. print_text(p) /* prints a token list */
  1200. text_pointer p;
  1201.   token_pointer j; /* index into |tok_mem| */
  1202.   sixteen_bits r; /* remainder of token after the flag has been stripped off */
  1203.   if (p>=text_ptr) printf("BAD");
  1204.   else for (j=*p; j<*(p+1); j++) {
  1205.     r=*j%id_flag;
  1206.     switch (*j/id_flag) {
  1207.       case 1: printf("\\{"); print_id((name_dir+r)); printf("}"); break;
  1208.     /* |id_flag| */
  1209.       case 2: printf("\&{"); print_id((name_dir+r)); printf("}"); break;
  1210.     /* |res_flag| */
  1211.       case 3: printf("<"); print_id((name_dir+r)); printf(">"); break;
  1212.         /* |mod_flag| */
  1213.       case 4: printf("[[%d]]",r); break; /* |tok_flag| */
  1214.       case 5: printf("|[[%d]]|",r); break; /* |inner_tok_flag| */
  1215.       default: @<Print token |r| in symbolic form@>;
  1216.     }
  1217. #endif DEBUG
  1218. @ @<Print token |r|...@>=
  1219. switch (r) {
  1220.   case math_bin: printf("\mathbin}"); break;
  1221.   case math_rel: printf("\mathrel}"); break;
  1222.   case big_cancel: printf("[ccancel]"); break;
  1223.   case cancel: printf("[cancel]"); break;
  1224.   case indent: printf("[indent]"); break;
  1225.   case outdent: printf("[outdent]"); break;
  1226.   case backup: printf("[backup]"); break;
  1227.   case opt: printf("[opt]"); break;
  1228.   case break_space: printf("[break]"); break;
  1229.   case force: printf("[force]"); break;
  1230.   case big_force: printf("[fforce]"); break;
  1231.   case end_translation: printf("[quit]"); break;
  1232.   default: putxchar(r);
  1233. @ The production rules listed above are embedded directly into the \.{WEAVE}
  1234. program, since it is easier to do this than to write an interpretive system
  1235. that would handle production systems in general. Several macros are defined
  1236. here so that the program for each production is fairly short.
  1237. All of our productions conform to the general notion that some |k|
  1238. consecutive scraps starting at some position |j| are to be replaced by a
  1239. single scrap of some category |c| whose translations is composed from the
  1240. translations of the disappearing scraps. After this production has been
  1241. applied, the production pointer |pp| should change by an amount |d|. Such
  1242. a production can be represented by the quadruple |(j,k,c,d)|. For example,
  1243. the production `|exp@,comma@,exp| $\RA$ |exp|' would be represented by
  1244. `|(pp,3,exp,-2)|'; in this case the pointer |pp| should decrease by 2
  1245. after the production has been applied, because some productions with
  1246. |exp| in their second or third positions might now match,
  1247. but no productions have
  1248. |math| in the fourth position of their left-hand sides. Note that
  1249. the value of |d| is determined by the whole collection of productions, not
  1250. by an individual one.
  1251. The determination of |d| has been
  1252. done by hand in each case, based on the full set of productions but not on
  1253. the grammar of \cee\ or on the rules for constructing the initial
  1254. scraps.
  1255. We also attach a serial number of each production, so that additional
  1256. information is available when debugging. For example, the program below
  1257. contains the statement `|reduce(pp,3,exp,-2,4)|' when it implements
  1258. the production just mentioned.
  1259. Before calling |reduce|, the program should have appended the tokens of
  1260. the new translation to the |tok_mem| array. We commonly want to append
  1261. copies of several existing translations, and macros are defined to
  1262. simplify these common cases. For example, |app2(pp)| will append the
  1263. translations of two consecutive scraps, |pp->trans| and |(pp+1)->trans|, to
  1264. the current token list. If the entire new translation is formed in this
  1265. way, we write `|squash(j,k,c,d)|' instead of `|reduce(j,k,c,d)|'. For
  1266. example, `|squash(pp,3,exp,-2,3)|' is an abbreviation for `|app3(pp);
  1267. reduce(pp,3,math,-2,3)|'.
  1268. A couple more words of explanation:
  1269. both |big_app| and |app| append a token (while |big_app1| to |big_app4|
  1270. append the specified number of scraps) to the current token list.
  1271. The difference between |big_app| and |app| is simply that |big_app|
  1272. checks whether there can be a conflict between math and non-math
  1273. tokens, and intercalates a `\.{\$}' token if necessary.  When in
  1274. doubt what to use, use |big_app|.
  1275. |mathness| is an attribute of scraps that says whether they are
  1276. to be printed in a math mode context or not.  It is separate from the
  1277. ``part of speech'' (the |cat|) because to make each |cat| have
  1278. a fixed |mathness| (as in the original web) would multiply the
  1279. number of necessary production rules.
  1280. The low two bits (i.e. |mathness % 4|) control the left boundary.
  1281. (We need two bits because we allow cases |yes_math|, |no_math| and
  1282. |maybe_math|, which can go either way.)
  1283. The next two bits (i.e. |mathness| / 4) control the right boundary.
  1284. If we combine two scraps and the right boundary of the first has
  1285. a different mathness from the left boundary of the second, we
  1286. insert a \.{\$} in between.  Similarly, if at printing time some
  1287. irreducible scrap has a |yes_math| boundary the scrap gets preceded
  1288. or followed by a \.{\$}.
  1289. The code below is an exact translation of the production rules into
  1290. \cee, using such macros, and the reader should have no difficulty
  1291. understanding the format by comparing the code with the symbolic
  1292. productions as they were listed earlier.
  1293. @d big_app2(a) big_app1(a);big_app1(a+1)
  1294. @d big_app3(a) big_app2(a);big_app1(a+2)
  1295. @d big_app4(a) big_app3(a);big_app1(a+3)
  1296. @d app(a) *(tok_ptr++)=a
  1297. @d app1(a) *(tok_ptr++)=tok_flag+(a)->trans-tok_start
  1298. @<Global...@>=
  1299. int cur_mathness, init_mathness;
  1300. @ @c app_str(s)
  1301. ASCII *s;
  1302.   while (*s) app(*(s++));
  1303. big_app(a)
  1304. token a;
  1305.     if (a==' ' || a>=big_cancel && a<=big_force) /* non-math token */ {
  1306.         if (cur_mathness==maybe_math) init_mathness=no_math;
  1307.         else if (cur_mathness==yes_math) app('$');
  1308.         cur_mathness=no_math;
  1309.     else {
  1310.         if (cur_mathness==maybe_math) init_mathness=yes_math;
  1311.         else if (cur_mathness==no_math) app('$');
  1312.         cur_mathness=yes_math;
  1313.     app(a);
  1314. big_app1(a)
  1315. scrap_pointer a;
  1316.   switch (a->mathness % 4) { /* left boundary */
  1317.   case (no_math):
  1318.     if (cur_mathness==maybe_math) init_mathness=no_math;
  1319.     else if (cur_mathness==yes_math) app('$');
  1320.     cur_mathness=a->mathness / 4; /* right boundary */
  1321.     break;
  1322.   case (yes_math):
  1323.     if (cur_mathness==maybe_math) init_mathness=yes_math;
  1324.     else if (cur_mathness==no_math) app('$');
  1325.     cur_mathness=a->mathness / 4; /* right boundary */
  1326.     break;
  1327.   case (maybe_math): /* no changes */ break;
  1328.   app(tok_flag+(a)->trans-tok_start);
  1329. @ Let us consider the big switch for productions now, before looking
  1330. at its context. We want to design the program so that this switch
  1331. works, so we might as well not keep ourselves in suspense about exactly what
  1332. code needs to be provided with a proper environment.
  1333. @<Match a production at |pp|, or increase |pp| if there is no match@>= {
  1334.   if (cat1==ignore_scrap) squash(pp,2,pp->cat,-2,56);
  1335.   else
  1336.   switch (pp->cat) {
  1337.     case exp: @<Cases for |exp|@>; break;
  1338.     case lpar: @<Cases for |lpar|@>; break;
  1339.     case question: @<Cases for |question|@>; break;
  1340.     case unop: @<Cases for |unop|@>; break;
  1341.     case unorbinop: @<Cases for |unorbinop|@>; break;
  1342.     case binop: @<Cases for |binop|@>; break;
  1343.     case cast: @<Cases for |cast|@>; break;
  1344.     case sizeof_like: @<Cases for |sizeof_like|@>; break;
  1345.     case int_like: @<Cases for |int_like|@>; break;
  1346.     case parms_like: @<Cases for |parms_like|@>; break;
  1347.     case decl_head: @<Cases for |decl_head|@>; break;
  1348.     case decl: @<Cases for |decl|@>; break;
  1349.     case typedef_like: @<Cases for |typedef_like|@>; break;
  1350.     case struct_like: @<Cases for |struct_like|@>; break;
  1351.     case struct_head: @<Cases for |struct_head|@>; break;
  1352.     case fn_decl: @<Cases for |fn_decl|@>; break;
  1353.     case function: @<Cases for |function|@>; break;
  1354.     case lbrace: @<Cases for |lbrace|@>; break;
  1355.     case do_like: @<Cases for |do_like|@>; break;
  1356.     case if_like: @<Cases for |if_like|@>; break;
  1357.     case else_like: @<Cases for |else_like|@>; break;
  1358.     case if_head: @<Cases for |if_head|@>; break;
  1359.     case case_like: @<Cases for |case_like|@>; break;
  1360.     case stmt: @<Cases for |stmt|@>; break;
  1361.     case tag: @<Cases for |tag|@>; break;
  1362.     case semi: @<Cases for |semi|@>; break;
  1363.     case lproc: @<Cases for |lproc|@>; break;
  1364.   pp++; /* if no match was found, we move to the right */
  1365. @ In \cee, new specifier names can be defined via |typedef|, and we want
  1366. to make the parser recognize future ocurrences of the identifier thus
  1367. defined as specifiers.  This is done by the procedure |make_reserved|,
  1368. which changes the |ilk| of the relevant identifier.
  1369. We first need a procedure to recursively seek the first
  1370. identifier in a token list, because the identifier might
  1371. be enclosed in parentheses, as when one defines a function
  1372. returning a pointer.
  1373. @d no_ident_found 0 /* distinct from any identifier token */
  1374. @c sixteen_bits
  1375. find_first_ident(p)
  1376. text_pointer p;
  1377.   sixteen_bits q; /* identifier to be returned */
  1378.   token_pointer j; /* token being looked at */
  1379.   sixteen_bits r; /* remainder of token after the flag has been stripped off */
  1380.   if (p>=text_ptr) confusion("find_first_ident");
  1381.   for (j=*p; j<*(p+1); j++) {
  1382.     r=*j%id_flag;
  1383.     switch (*j/id_flag) {
  1384.       case 1: return *j;
  1385.       case 4: case 5:
  1386.         if ((q=find_first_ident(tok_start+r))!=no_ident_found)
  1387.           return q;
  1388.       default: ; /* move on to next token */
  1389.     }
  1390.   return no_ident_found;
  1391. @ The scraps currently being parsed must be inspected for any
  1392. occurrence of the identifier that we're making reserved; hence
  1393. the |for| loop below.
  1394. @c make_reserved(p) /* make the first identifier in |p->trans| like |int| */
  1395. scrap_pointer p;
  1396.   sixteen_bits tok_value; /* the name of this identifier, plus its flag*/
  1397.   if ((tok_value=find_first_ident(p->trans))==no_ident_found)
  1398.     return; /* this should not happen */
  1399.   for (;p<=scrap_ptr; p++) {
  1400.     if (p->cat==exp) {
  1401.       if (**(p->trans)==tok_value) {
  1402.         p->cat=int_like;
  1403.         **(p->trans)+=res_flag-id_flag;
  1404.       }
  1405.     }
  1406.   (name_dir+tok_value-id_flag)->ilk=int_like;
  1407. @ In the following situations we want to mark the occurrence of
  1408. an identifier as a definition: when |make_reserved| has just been
  1409. used; after a specifier, as in |char **argv|;
  1410. before a colon, as in |found:|; and in the declaration of a function,
  1411. as in |main(){@t\dots@>;}|.  This is accomplished by the invocation
  1412. of |make_underlined| at appropriate times.  Since, in the declaration
  1413. of a function, we only find out that the identifier is being defined after
  1414. it has been swallowed up by an |exp|, we must make this procedure
  1415. recursive.
  1416. @c make_underlined(p)
  1417. /* underline the entry for the first identifier in |p->trans| */
  1418. scrap_pointer p;
  1419.   sixteen_bits tok_value; /* the name of this identifier, plus its flag */
  1420.   if ((tok_value=find_first_ident(p->trans))==no_ident_found)
  1421.     return; /* this happens after parsing the |()| in |double f();| */
  1422.   xref_switch=def_flag; underline_xref(tok_value-id_flag+name_dir);
  1423. @ We cannot use |new_xref| to underline a cross-reference at this point
  1424. because this would just make a new cross-reference at the end of the list.
  1425. We actually have to search through the list for the existing
  1426. cross-reference.
  1427. @c underline_xref(p)
  1428. name_pointer p;
  1429.   xref_pointer q=(xref_pointer)p->xref; /* pointer to cross-reference being examined */
  1430.   xref_pointer r; /* temporary pointer for permuting cross-references */
  1431.   sixteen_bits m; /* cross-reference value to be installed */
  1432.   sixteen_bits n; /* cross-reference value being examined */
  1433.   if (no_xref) return;
  1434.   xref_switch=def_flag;
  1435.   m=module_count+xref_switch;
  1436.   while (q != xmem) {
  1437.     n=q->num;
  1438.     if (n==m) return;
  1439.     else if (m==n+def_flag) {
  1440.     q->num=m; return;
  1441.     }
  1442.     else if (n>=def_flag && n<m) break;
  1443.     q=q->xlink;
  1444.   @<Insert new cross-reference at |q|, not at beginning of list@>;
  1445. @ We get to this module only when the identifier is one letter long,
  1446. so it didn't get a non-underlined entry during phase one.  But it may
  1447. have got some explicitly underlined entries in later modules, so in order
  1448. to preserve the numerical order of the entries in the index, we have
  1449. to insert the new cross-reference not at the beginning of the list
  1450. (namely, at |p->xref|), but rather right before |q|.
  1451. @<Insert new cross-reference at |q|...@>=
  1452.   append_xref(0); /* this number doesn't matter */
  1453.   xref_ptr->xlink=(xref_pointer)p->xref; r=xref_ptr;
  1454.   p->xref=(char*)xref_ptr;
  1455.   while (r->xlink!=q) {r->num=r->xlink->num; r=r->xlink;}
  1456.   r->num=m; /* everything from |q| on is left undisturbed */
  1457. @ Now comes the code that tries to match each production that starts
  1458. with a particular type of scrap. Whenever a match is discovered,
  1459. the |squash| or |reduce| macro will cause the appropriate action
  1460. to be performed, followed by |goto found|.
  1461. @d cat1 (pp+1)->cat
  1462. @d cat2 (pp+2)->cat
  1463. @d cat3 (pp+3)->cat
  1464. @<Cases for |exp|@>=
  1465. if (cat1==lbrace || cat1==int_like) {
  1466.   make_underlined(pp); squash(pp,1,fn_decl,0,1);
  1467. else if (cat1==unop) squash(pp,2,exp,-2,2);
  1468. else if ((cat1==binop || cat1==unorbinop) && cat2==exp)
  1469.     squash(pp,3,exp,-2,3);
  1470. else if (cat1==comma && cat2==exp) {
  1471.   big_app1(pp); big_app(',');
  1472.   app(opt); app('9'); big_app1(pp+2); reduce(pp,3,exp,-2,4);
  1473. else if (cat1==exp) squash(pp,2,exp,-2,5);
  1474. else if (cat1==semi) squash(pp,2,stmt,-1,6);
  1475. else if (cat1==colon) {
  1476.   make_underlined (pp);  squash(pp,2,tag,0,7);
  1477. @ @<Cases for |lpar|@>=
  1478. if (cat1==exp && cat2==rpar) squash(pp,3,exp,-2,8);
  1479. else if (cat1==rpar) {
  1480.   big_app1(pp); big_app('\\'); big_app(','); big_app1(pp+1);
  1481.   reduce(pp,2,exp,-2,9);
  1482. else if ((cat1==decl_head || cat1==int_like) && cat2==rpar)
  1483.   squash(pp,3,cast,-1,10);
  1484. else if (cat1==stmt) {
  1485.   big_app2(pp); big_app(' '); reduce(pp,2,lpar,0,11);
  1486. @ @<Cases for |question|@>=
  1487. if (cat1==exp && cat2==colon) squash(pp,3,binop,-2,12);
  1488. @ @<Cases for |unop|@>=
  1489. if (cat1==exp) squash(pp,2,exp,-2,13);
  1490. @ @<Cases for |unorbinop|@>=
  1491. if (cat1==exp || cat1==int_like) {
  1492.   big_app('{'); big_app1(pp); big_app('}'); big_app1(pp+1);
  1493.   reduce(pp,2,exp,-2,14);
  1494. else if (cat1==binop) {
  1495.   big_app(math_bin); big_app1(pp); big_app('{'); big_app1(pp+1); big_app('}');
  1496.   big_app('}'); reduce(pp,2,binop,-1,15);
  1497. @ @<Cases for |binop|@>=
  1498. if (cat1==binop) {
  1499.   big_app(math_bin); big_app1(pp); big_app('{'); big_app1(pp+1); big_app('}');
  1500.   big_app('}'); reduce(pp,2,binop,-1,16);
  1501. @ @<Cases for |cast|@>=
  1502. if (cat1==exp) {
  1503.   big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,exp,-2,17);
  1504. @ @<Cases for |sizeof_like|@>=
  1505. if (cat1==cast) squash(pp,2,exp,-2,18);
  1506. else if (cat1==exp) {
  1507.   big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,exp,-2,19);
  1508. @ @<Cases for |int_like|@>=
  1509. if (cat1==int_like|| cat1==struct_like) {
  1510.   big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,cat1,-1,20);
  1511. else if (cat1==exp || cat1==unorbinop || cat1==semi) {
  1512.   big_app1(pp); big_app(' '); reduce(pp,1,decl_head,-1,21);
  1513. @ @<Cases for |parms_like|@>=
  1514. if (cat1==lpar || cat1==int_like || cat1==decl_head || cat1==exp) {
  1515.   big_app2(pp); reduce(pp,2,parms_like,0,80);
  1516. else if (cat1==comma) {
  1517.   big_app2(pp); big_app(' '); reduce(pp,2,parms_like,0,80);
  1518. else if (cat1==unorbinop) {
  1519.   big_app(' '); big_app1(pp); big_app('{'); big_app1(pp+1); big_app('}');
  1520.   reduce(pp,2,parms_like,0,80);
  1521. else if (cat1==rpar && cat2==rpar) {
  1522.   big_app(break_space); big_app3(pp); reduce(pp,3,ignore_scrap,-3,80);
  1523. @ @<Cases for |decl_head|@>=
  1524. if (cat1==comma) {
  1525.   big_app2(pp); big_app(' '); reduce(pp,2,decl_head,-1,22);
  1526. else if (cat1==unorbinop) {
  1527.   big_app1(pp); big_app('{'); big_app1(pp+1); big_app('}');
  1528.   reduce(pp,2,decl_head,-1,23);
  1529. else if (cat1==exp) {
  1530.   make_underlined(pp+1); squash(pp,2,decl_head,0,24);
  1531. else if ((cat1==binop||cat1==colon) && cat2==exp && (cat3==comma || cat3==semi))
  1532.   squash(pp,3,decl_head,-1,25);
  1533. else if (cat1==lbrace || cat1==int_like) squash(pp,1,fn_decl,0,26);
  1534. else if (cat1==semi) squash(pp,2,decl,-1,27);
  1535. @ @<Cases for |decl|@>=
  1536. if (cat1==decl) {
  1537.   big_app1(pp); big_app(force); big_app1(pp+1);
  1538.   reduce(pp,2,decl,-1,28);
  1539. else if (cat1==stmt || cat1==function) {
  1540.   big_app1(pp); big_app(big_force); big_app1(pp+1); reduce(pp,2,cat1,-1,29);
  1541. @ @<Cases for |typedef_like|@>=
  1542. if (cat1==decl_head)
  1543.   if (cat2==exp||cat2==int_like) {
  1544.     make_underlined(pp+2); make_reserved(pp+2);
  1545.     big_app2(pp+1); reduce(pp+1,2,decl_head,0,30);
  1546.   else if (cat2==semi) {
  1547.     big_app1(pp); big_app(' '); big_app2(pp+1); reduce(pp,3,decl,0,31);
  1548. @ @<Cases for |struct_like|@>=
  1549. if (cat1==lbrace) {
  1550.   big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,struct_head,0,32);
  1551. else if (cat1==exp||cat1==int_like) {
  1552.   if (cat2==lbrace) {
  1553.     big_app1(pp); big_app(' '); big_app1(pp+1);
  1554.     big_app(' '); big_app1(pp+2);reduce(pp,3,struct_head,0,33);
  1555.   else {
  1556.     big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,int_like,-1,34);
  1557. @ @<Cases for |struct_head|@>=
  1558. if ((cat1==decl || cat1==stmt) && cat2==rbrace) {
  1559.   big_app1(pp); big_app(indent); big_app(force); big_app1(pp+1);
  1560.   big_app(outdent); big_app(force);  big_app1(pp+2); 
  1561.   reduce(pp,3,int_like,-1,35);
  1562. @ @<Cases for |fn_decl|@>=
  1563. if (cat1==decl) {
  1564.   big_app1(pp); big_app(force); big_app1(pp+1); reduce(pp,2,fn_decl,0,36);
  1565. else if (cat1==stmt) {
  1566.   big_app1(pp); big_app(force); big_app1(pp+1); reduce(pp,2,function,-1,37);
  1567. @ @<Cases for |function|@>=
  1568. if (cat1==function || cat1==decl) {
  1569.   big_app1(pp); big_app(big_force); big_app1(pp+1); reduce(pp,2,cat1,0,38);
  1570. @ @<Cases for |lbrace|@>=
  1571. if (cat1==rbrace) {
  1572.   big_app1(pp); big_app('\\'); big_app(','); big_app1(pp+1); 
  1573.   reduce(pp,2,stmt,-1,39);
  1574. else if (cat1==stmt && cat2==rbrace) {
  1575.   big_app(force); big_app1(pp);  big_app(indent); big_app(force);
  1576.   big_app1(pp+1); big_app(force); big_app(backup);  big_app1(pp+2); 
  1577.   big_app(outdent); big_app(force); reduce(pp,3,stmt,-1,40);
  1578. else if (cat1==exp) {
  1579.   if (cat2==rbrace) squash(pp,3,exp,-2,41);
  1580.   else if (cat2==comma && cat3==rbrace) squash(pp,4,exp,-2,41);
  1581. @ @<Cases for |if_like|@>=
  1582. if (cat1==exp) {
  1583.   big_app1(pp); big_app(' '); big_app1(pp+1); reduce(pp,2,else_like,0,42);
  1584. @ @<Cases for |else_like|@>=
  1585. if (cat1==lbrace) squash(pp,1,if_head,0,43);
  1586. else if (cat1==stmt) {
  1587.   big_app(force); big_app1(pp); big_app(indent); big_app(break_space);
  1588.   big_app1(pp+1); big_app(outdent); big_app(force);
  1589.   if (cat2==else_like) {
  1590.     big_app1(pp+2); big_app(' '); big_app(cancel); reduce(pp,3,else_like,0,44);
  1591.   else reduce(pp,2,stmt,-1,45);
  1592. @ @<Cases for |if_head|@>=
  1593. if (cat1==stmt) {
  1594.   big_app(force); big_app1(pp); big_app(break_space);
  1595.   big_app('{'); big_app('}'); big_app(cancel); big_app1(pp+1);
  1596.   if (cat2==else_like) {
  1597.     big_app(break_space); big_app1(pp+2); big_app(' '); big_app(cancel);
  1598.     reduce(pp,3,else_like,0,46);
  1599.   else {
  1600.     big_app(force); reduce(pp,2,stmt,-1,47);
  1601. @ @<Cases for |do_like|@>=
  1602. if (cat1==stmt && cat2==if_like) {
  1603.   big_app1(pp); big_app(break_space); big_app1(pp+1);
  1604.   big_app(break_space); big_app1(pp+2); reduce(pp,3,if_like,0,48);
  1605. @ @<Cases for |case_like|@>=
  1606. if (cat1==semi) squash(pp,2,stmt,-1,49);
  1607. else if (cat1==colon) squash(pp,2,tag,-1,51);
  1608. else if (cat1==exp) {
  1609.   if (cat2==semi) {
  1610.     big_app1(pp); big_app(' ');  big_app1(pp+1);  big_app1(pp+2);
  1611.     reduce(pp,3,stmt,-1,50);
  1612.   else if (cat2==colon) {
  1613.     big_app1(pp); big_app(' ');  big_app1(pp+1);  big_app1(pp+2);
  1614.     reduce(pp,3,tag,-1,52);
  1615. @ @<Cases for |tag|@>=
  1616. if (cat1==tag) {
  1617.   big_app1(pp); big_app(break_space); big_app1(pp+1); reduce(pp,2,tag,-1,53);
  1618. else if (cat1==stmt) {
  1619.   big_app(force); big_app(backup); big_app1(pp); big_app(break_space);
  1620.   big_app1(pp+1); reduce(pp,2,stmt,-1,54);
  1621. @ @<Cases for |stmt|@>=
  1622. if (cat1==stmt) {
  1623.   big_app1(pp); big_app(force); big_app1(pp+1); reduce(pp,2,stmt,-1,55);
  1624. @ @<Cases for |semi|@>=
  1625. big_app(' '); big_app1(pp); reduce(pp,1,stmt,-1,56);
  1626. @ @<Cases for |lproc|@>=
  1627. if (cat1==define_like) make_underlined(pp+2);
  1628. if (cat1==else_like || cat1==if_like ||cat1==define_like)
  1629.   squash(pp,2,lproc,0,57);
  1630. else if (cat1==rproc) squash(pp,2,ignore_scrap,-1,58);
  1631. else if (cat1==exp) {
  1632.   if (cat2==rproc) {
  1633.     big_app1(pp); big_app(' '); big_app2(pp+1);
  1634.     reduce(pp,3,ignore_scrap,-1,59);
  1635.   else if (cat2==exp && cat3==rproc) {
  1636.     big_app1(pp); big_app(' '); big_app1(pp+1); big_app(break_space);
  1637.     big_app2(pp+2); reduce(pp,4,ignore_scrap,-1,59);
  1638. @ The `|freeze_text|' macro is used to give official status to a token list.
  1639. Before saying |freeze_text|, items are appended to the current token list,
  1640. and we know that the eventual number of this token list will be the current
  1641. value of |text_ptr|. But no list of that number really exists as yet,
  1642. because no ending point for the current list has been
  1643. stored in the |tok_start| array. After saying |freeze_text|, the
  1644. old current token list becomes legitimate, and its number is the current
  1645. value of |text_ptr-1| since |text_ptr| has been increased. The new
  1646. current token list is empty and ready to be appended to.
  1647. Note that |freeze_text| does not check to see that |text_ptr| hasn't gotten
  1648. too large, since it is assumed that this test was done beforehand.
  1649. @d freeze_text *(++text_ptr)=tok_ptr
  1650. @ Here's the |reduce| procedure used in our code for productions:
  1651. @c reduce(j,k,c,d,n)
  1652. scrap_pointer j;
  1653. eight_bits c;
  1654. short k, d, n;
  1655.   scrap_pointer i, i1; /* pointers into scrap memory */
  1656.   j->cat=c; j->trans=text_ptr;
  1657.   j->mathness=4*cur_mathness+init_mathness;
  1658.   freeze_text;
  1659.   if (k>1) {
  1660.     for (i=j+k, i1=j+1; i<=lo_ptr; i++, i1++) {
  1661.       i1->cat=i->cat; i1->trans=i->trans;
  1662.       i1->mathness=i->mathness;
  1663.     }
  1664.     lo_ptr=lo_ptr-k+1;
  1665.   @<Change |pp| to $\max(|scrap_base|,|pp+d|)$@>;
  1666. #ifdef DEBUG
  1667.   @<Print a snapshot of the scrap list if debugging @>;
  1668. #endif DEBUG
  1669.   pp--; /* we next say |pp++| */
  1670. @ @<Change |pp| to $\max...@>=
  1671. if (pp+d>=scrap_base) pp=pp+d;
  1672. else pp=scrap_base;
  1673. @ Here's the |squash| procedure, which
  1674. takes advantage of the simplification that occurs when |k=1|.
  1675. @c squash(j,k,c,d,n)
  1676. scrap_pointer j;
  1677. eight_bits c;
  1678. short k, d, n;
  1679.   scrap_pointer i; /* pointers into scrap memory */
  1680.   if (k==1) {
  1681.     j->cat=c; @<Change |pp|...@>;
  1682. #ifdef DEBUG
  1683.     @<Print a snapshot...@>;
  1684. #endif DEBUG
  1685.     pp--; /* we next say |pp++| */
  1686.     return;
  1687.   for (i=j; i<j+k; i++) big_app1(i);
  1688.   reduce(j,k,c,d,n);
  1689. @ Here now is the code that applies productions as long as possible.
  1690. Before applying the prodcution mechanism, we must make sure
  1691. it has good input (at least four scraps, the length of the lhs of the
  1692. longest rules), and that there is enough room in the memory arrays
  1693. to hold the appended tokens and texts.  Here we use a very
  1694. conservative test: it's more important to make sure the program
  1695. will still work if we change the production rules (within reason)
  1696. than to squeeze the last bit of space from the memory arrays.
  1697. @d safe_tok_incr 20
  1698. @d safe_text_incr 10
  1699. @d safe_scrap_incr 10
  1700. @<Reduce the scraps using the productions until no more rules apply@>=
  1701. while (1) {
  1702.   @<Make sure the entries |pp| through |pp+3| of |cat| are defined@>;
  1703.   if (tok_ptr+safe_tok_incr>tok_mem_end) {
  1704. #ifdef STAT
  1705.     if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
  1706. #endif STAT
  1707.     overflow("token");
  1708.   if (text_ptr+safe_text_incr>tok_start_end) {
  1709. #ifdef STAT
  1710.     if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
  1711. #endif STAT
  1712.     overflow("text");
  1713.   if (pp>lo_ptr) break;
  1714.   init_mathness=cur_mathness=maybe_math;
  1715.   @<Match a production...@>;
  1716. @ If we get to the end of the scrap list, category codes equal to zero are
  1717. stored, since zero does not match anything in a production.
  1718. @<Make sure the entries...@>=
  1719. if (lo_ptr<pp+3) {
  1720.   while (hi_ptr<=scrap_ptr && lo_ptr!=pp+3) {
  1721.     (++lo_ptr)->cat=hi_ptr->cat; lo_ptr->mathness=(hi_ptr)->mathness;
  1722.     lo_ptr->trans=(hi_ptr++)->trans;
  1723.   for (i=lo_ptr+1;i<=pp+3;i++) i->cat=0;
  1724. @ If \.{WEAVE} is being run in debugging mode, the production numbers and
  1725. current stack categories will be printed out when |tracing| is set to 2;
  1726. a sequence of two or more irreducible scraps will be printed out when
  1727. |tracing| is set to 1.
  1728. @<Global...@>=
  1729. #ifdef DEBUG
  1730. int tracing; /* can be used to show parsing details */
  1731. #endif DEBUG
  1732. @ @<Print a snapsh...@>= {
  1733.   scrap_pointer k; /* pointer into |scrap_info| */
  1734.   if (tracing==2) {
  1735.     printf("\n%d:",n);
  1736.     for (k=scrap_base; k<=lo_ptr; k++) {
  1737.       if (k==pp) putxchar('*'); else putxchar(' ');
  1738.       if (k->mathness %4 ==  yes_math) putchar('+');
  1739.       else if (k->mathness %4 ==  no_math) putchar('-');
  1740.       print_cat(k->cat);
  1741.       if (k->mathness /4 ==  yes_math) putchar('+');
  1742.       else if (k->mathness /4 ==  no_math) putchar('-');
  1743.     }
  1744.     if (hi_ptr<=scrap_ptr) printf("..."); /* indicate that more is coming */
  1745. @ The |translate| function assumes that scraps have been stored in
  1746. positions |scrap_base| through |scrap_ptr| of |cat| and |trans|. It
  1747. appends a |terminator| scrap and begins to apply productions as much as
  1748. possible. The result is a token list containing the translation of
  1749. the given sequence of scraps.
  1750. After calling |translate|, we will have |text_ptr+3<=max_texts| and
  1751. |tok_ptr+6<=max_toks|, so it will be possible to create up to three token
  1752. lists with up to six tokens without checking for overflow. Before calling
  1753. |translate|, we should have |text_ptr<max_texts| and |scrap_ptr<max_scraps|,
  1754. since |translate| might add a new text and a new scrap before it checks
  1755. for overflow.
  1756. @c text_pointer translate() /* converts a sequence of scraps */
  1757.   scrap_pointer i, /* index into |cat| */
  1758.   j; /* runs through final scraps */
  1759.   pp=scrap_base; lo_ptr=pp-1; hi_ptr=pp;
  1760.   @<If tracing, print an indication of where we are@>;
  1761.   @<Reduce the scraps...@>;
  1762.   @<Combine the irreducible scraps that remain@>;
  1763. @ If the initial sequence of scraps does not reduce to a single scrap,
  1764. we concatenate the translations of all remaining scraps, separated by
  1765. blank spaces, with dollar signs surrounding the translations of scraps
  1766. whose category code is |max_math| or less.
  1767. @<Combine the irreducible...@>= {
  1768.   @<If semi-tracing, show the irreducible scraps@>;
  1769.   for (j=scrap_base; j<=lo_ptr; j++) {
  1770.     if (j!=scrap_base) app(' ');
  1771.     if ((j->mathness % 4 == yes_math) && math_flag==0) app('$');
  1772.     if ((j->mathness % 4 == no_math) && math_flag==1) {
  1773.     app(' '); app('$');}
  1774.     app1(j);
  1775.     if ((j->mathness / 4 == yes_math) && math_flag==0) app('$');
  1776.     if ((j->mathness / 4 == no_math) && math_flag==1) {app('$');
  1777.     app(' ');}
  1778.     if (tok_ptr+6>tok_mem_end) overflow("token");
  1779.   freeze_text; return(text_ptr-1);
  1780. @ @<If semi-tracing, show the irreducible scraps@>=
  1781. #ifdef DEBUG
  1782. if (lo_ptr>scrap_base && tracing==1) {
  1783.   printf("Irreducible scrap sequence in section %d:",module_count);
  1784.   mark_harmless;
  1785.   for (j=scrap_base; j<=lo_ptr; j++) {
  1786.     printf(" "); print_cat(j->cat);
  1787. #endif DEBUG
  1788. @ @<If tracing,...@>=
  1789. #ifdef DEBUG
  1790. if (tracing==2) {
  1791.   printf("\nTracing after l. %d:\n",cur_line); mark_harmless;
  1792.   if (loc>buffer+50) {
  1793.     printf("...");
  1794.     ASCII_write(loc-51,51);
  1795.   else ASCII_write(buffer+1,loc-buffer);
  1796. #endif DEBUG
  1797. @* Initializing the scraps.
  1798. If we are going to use the powerful production mechanism just developed, we
  1799. must get the scraps set up in the first place, given a \cee\ text. A table
  1800. of the initial scraps corresponding to \cee\ tokens appeared above in the
  1801. section on parsing; our goal now is to implement that table. We shall do this
  1802. by implementing a subroutine called |C_parse| that is analogous to the
  1803. |C_xref| routine used during phase one.
  1804. Like |C_xref|, the |C_parse| procedure starts with the current
  1805. value of |next_control| and it uses the operation |next_control:=get_next|
  1806. repeatedly to read \cee\ text until encountering the next `\.{\v}' or
  1807. `\.\{', or until |next_control>=format|. The scraps corresponding to what
  1808. it reads are appended into the |cat| and |trans| arrays, and |scrap_ptr|
  1809. is advanced.
  1810. @c C_parse() /* creates scraps from \cee\ tokens */
  1811.   name_pointer p; /* identifier designator */
  1812.   while (next_control<format) {
  1813.     @<Append the scrap appropriate to |next_control|@>;
  1814.     next_control=get_next();
  1815.     if (next_control=='|' || next_control==begin_comment) return;
  1816. @ The following macro is used to append a scrap whose tokens have just
  1817. been appended:
  1818. @d app_scrap(c,b) (++scrap_ptr)->cat=c; scrap_ptr->trans=text_ptr;
  1819. scrap_ptr->mathness=5*b;
  1820. freeze_text;
  1821. @ @<Append the scr...@>=
  1822. @<Make sure that there is room for the new scraps, tokens, and texts@>;
  1823. switch (next_control) {
  1824.   case string: case constant: case verbatim: @<Append a string or constant@>;
  1825.     break;
  1826.   case identifier: @<Append an identifier scrap@>; break;
  1827.   case TeX_string: @<Append a \TeX\ string scrap@>; break;
  1828.   case '+': case '/': case '<': case '>': case '.': case '|':
  1829.     app(next_control); app_scrap(binop,yes_math); break;
  1830.   case '=': app_str("\\K"); app_scrap(binop,yes_math); break;
  1831.   case '^': case '%': app('\\'); app(next_control);
  1832.     app_scrap(binop,yes_math); break;
  1833.   case '!': app_str("\\R"); app_scrap(unop,yes_math); break;
  1834.   case '~': app('\\'); app(next_control); app_scrap(unop,yes_math); break;
  1835.   case '-': case '*': app(next_control); app_scrap(unorbinop,yes_math); break;
  1836.   case '&': app_str("\\amp"); app_scrap(unorbinop,yes_math); break;
  1837.   case '?': app_str("\\?"); app_scrap(question,yes_math); break;
  1838.   case '#': app_str("\\#"); app_scrap(ignore_scrap,maybe_math); break;
  1839.     /* this shouldn't happen */
  1840.   case ignore: case xref_roman: case xref_wildcard:
  1841.   case xref_typewriter: break;
  1842.   case '(': case '[': app(next_control); app_scrap(lpar,maybe_math); break;
  1843.   case ')': case ']': app(next_control); app_scrap(rpar,maybe_math); break;
  1844.   case '{': app_str("\\{"); app_scrap(lbrace,yes_math); break;
  1845.   case '}': app_str("\\}"); app_scrap(rbrace,yes_math); break;
  1846.   case ',': app(','); app_scrap(comma,maybe_math); break;
  1847.   case ';': app(';'); app_scrap(semi,maybe_math); break;
  1848.   case ':': app(':'); app_scrap(colon,maybe_math); break;
  1849.   @t\4@>  @<Cases involving nonstandard ASCII characters@>@;
  1850.   case force_line: app_str("\\]"); app_scrap(ignore_scrap,yes_math); break;
  1851.   case thin_space: app_str("\\,"); app_scrap(ignore_scrap,yes_math); break;
  1852.   case math_break: app(opt); app_str("0");
  1853.     app_scrap(ignore_scrap,yes_math); break;
  1854.   case line_break: app(force); app_scrap(ignore_scrap,no_math); break;
  1855.   case left_preproc: app(force); app(preproc_line);
  1856.     app_str("\\#"); app_scrap(lproc,no_math); break;
  1857.   case right_preproc: app(force); app_scrap(rproc,no_math); break;
  1858.   case big_line_break: app(big_force); app_scrap(ignore_scrap,no_math); break;
  1859.   case no_line_break: app(big_cancel); app_str("{}"); app(break_space);
  1860.     app_str("{}"); app(big_cancel);
  1861.     app_scrap(ignore_scrap,no_math); break;
  1862.   case pseudo_semi: app_scrap(semi,maybe_math); break;
  1863.   case join: app_str("\\J"); app_scrap(ignore_scrap,no_math); break;
  1864.   default: app(next_control); app_scrap(ignore_scrap,maybe_math); break;
  1865. @ @<Make sure that there is room for the new...@>=
  1866. if (scrap_ptr+safe_scrap_incr>scrap_info_end ||
  1867.   tok_ptr+safe_tok_incr>tok_mem_end ||
  1868.   text_ptr+safe_text_incr>tok_start_end) {
  1869. #ifdef STAT
  1870.   if (scrap_ptr>max_scr_ptr) max_scr_ptr=scrap_ptr;
  1871.   if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
  1872.   if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
  1873. #endif STAT
  1874.   overflow("scrap/token/text");
  1875. @ Some nonstandard ASCII characters may have entered \.{WEAVE} by means of
  1876. standard ones. They are converted to \TeX\ control sequences so that it is
  1877. possible to keep \.{WEAVE} from stepping beyond standard ASCII.
  1878. @<Cases involving nonstandard...@>=
  1879. case not_eq: app_str("\\I"); app_scrap(binop,yes_math); break;
  1880. case lt_eq: app_str("\\L"); app_scrap(binop,yes_math); break;
  1881. case gt_eq: app_str("\\G"); app_scrap(binop,yes_math); break;
  1882. case eq_eq: app_str("\\S"); app_scrap(binop,yes_math); break;
  1883. case and_and: app_str("\\W"); app_scrap(binop,yes_math); break;
  1884. case or_or: app_str("\\V"); app_scrap(binop,yes_math); break;
  1885. case plus_plus: app_str("\\PP"); app_scrap(unop,yes_math); break;
  1886. case minus_minus: app_str("\\MM"); app_scrap(unop,yes_math); break;
  1887. case minus_gt: app_str("\\MG"); app_scrap(binop,yes_math); break;
  1888. case gt_gt: app_str("\\GG"); app_scrap(binop,yes_math); break;
  1889. case lt_lt: app_str("\\LL"); app_scrap(binop,yes_math); break;
  1890. @ The following code must use |app_tok| instead of |app| in order to
  1891. protect against overflow. Note that |tok_ptr+1<=max_toks| after |app_tok|
  1892. has been used, so another |app| is legitimate before testing again.
  1893. Many of the special characters in a string must be prefixed by `\.\\' so that
  1894. \TeX\ will print them properly.
  1895. @^special string characters@>
  1896. @<Append a string or...@>=
  1897. if (next_control==constant) app_str("\\O{");
  1898. @.\\O@>
  1899. else if (next_control==string) app_str("\\){");
  1900. @.\\)@>
  1901. else app_str("\\={");
  1902. @.\\=@>
  1903. while (id_first<id_loc) {
  1904.   switch (*id_first) {
  1905.     case  ' ':case '\\':case '#':case '%':case '$':case '^':case '`':
  1906.     case '{': case '}': case '~': case '&': case '_': app('\\'); break;
  1907.     case '@@': if (*(id_first+1)=='@@') id_first++;
  1908.       else err_print("! Double @@ should be used in strings");
  1909. @.Double {\AT} should be used...@>
  1910.   app_tok(*id_first++);
  1911. app('}');
  1912. if (next_control==constant) {app_scrap(exp,yes_math);}
  1913. else {app_scrap(exp,no_math);}
  1914. @ @<Append a \TeX\ string scrap@>=
  1915. app_str("\\hbox{"); while (id_first<id_loc) app_tok(*id_first++);
  1916. app('}'); app_scrap(exp,maybe_math);
  1917. @ @<Append an identifier scrap@>=
  1918. p=id_lookup(id_first, id_loc,normal);
  1919. if (p->ilk==normal) {
  1920.   app(id_flag+p-name_dir); app_scrap(exp,maybe_math); /* not a reserved word */
  1921. else {
  1922.   app(res_flag+p-name_dir);
  1923.   app_scrap(p->ilk,0);
  1924. @ When the `\.{\v}' that introduces \cee\ text is sensed, a call on
  1925. |C_translate| will return a pointer to the \TeX\ translation of
  1926. that text. If scraps exist in |scrap_info|, they are
  1927. unaffected by this translation process.
  1928. @c text_pointer C_translate()
  1929.   text_pointer p; /* points to the translation */
  1930.   scrap_pointer save_base; /* holds original value of |scrap_base| */
  1931.   save_base=scrap_base; scrap_base=scrap_ptr+1;
  1932.   C_parse(); /* get the scraps together */
  1933.   if (next_control!='|') err_print("! Missing '|' after C text");
  1934. @.Missing '|'...@>
  1935.   app_tok(cancel); app_scrap(ignore_scrap,maybe_math);
  1936.     /* place a |cancel| token as a final ``comment'' */
  1937.   p=translate(); /* make the translation */
  1938. #ifdef STAT
  1939.  if (scrap_ptr>max_scr_ptr) max_scr_ptr=scrap_ptr;
  1940. #endif STAT
  1941.   scrap_ptr=scrap_base-1; scrap_base=save_base; /* scrap the scraps */
  1942.   return(p);
  1943. @ The |outer_parse| routine is to |C_parse| as |outer_xref|
  1944. is to |C_xref|: it constructs a sequence of scraps for \cee\ text
  1945. until |next_control>=format|. Thus, it takes care of embedded comments.
  1946. @c outer_parse() /* makes scraps from \cee\ tokens and comments */
  1947.   int bal; /* brace level in comment */
  1948.   text_pointer p, q; /* partial comments */
  1949.   while (next_control<format)
  1950.     if (next_control!=begin_comment) C_parse();
  1951.     else {
  1952.       @<Make sure that there is room for the new...@>;
  1953.       app(cancel); app_str("\\5\\C{");
  1954.     /* append an explicit |break_space|, so it won't be canceled */
  1955. @.\\4@>
  1956. @.\\C@>
  1957.       bal=copy_comment(1); next_control=ignore;
  1958.       while (bal>0) {
  1959.     p=text_ptr; freeze_text; q=C_translate();
  1960.          /* at this point we have |tok_ptr+6<=max_toks| */
  1961.         app(tok_flag+p-tok_start); app(inner_tok_flag+q-tok_start);
  1962.         if (next_control=='|') {
  1963.       bal=copy_comment(bal);
  1964.       next_control=ignore;
  1965.         else bal=0; /* an error has been reported */
  1966.       }
  1967.       app(force); app_scrap(ignore_scrap,no_math);
  1968.     /* the full comment becomes a scrap */
  1969.     }
  1970. @* Output of tokens.
  1971. So far our programs have only built up multi-layered token lists in
  1972. \.{WEAVE}'s internal memory; we have to figure out how to get them into
  1973. the desired final form. The job of converting token lists to characters in
  1974. the \TeX\ output file is not difficult, although it is an implicitly
  1975. recursive process. Three main considerations had to be kept in mind when
  1976. this part of \.{WEAVE} was designed:  (a) There are two modes of output,
  1977. |outer| mode that translates tokens like |force| into line-breaking
  1978. control sequences, and |inner| mode that ignores them except that blank
  1979. spaces take the place of line breaks. (b) The |cancel| instruction applies
  1980. to adjacent token or tokens that are output, and this cuts across levels
  1981. of recursion since `|cancel|' occurs at the beginning or end of a token
  1982. list on one level. (c) The \TeX\ output file will be semi-readable if line
  1983. breaks are inserted after the result of tokens like |break_space| and
  1984. |force|.  (d) The final line break should be suppressed, and there should
  1985. be no |force| token output immediately after `\.{\\Y\\P}'.
  1986. @ The output process uses a stack to keep track of what is going on at
  1987. different ``levels'' as the token lists are being written out. Entries on
  1988. this stack have three parts:
  1989. \yskip\hang |end_field| is the |tok_mem| location where the token list of a
  1990. particular level will end;
  1991. \yskip\hang |tok_field| is the |tok_mem| location from which the next token
  1992. on a particular level will be read;
  1993. \yskip\hang |mode_field| is the current mode, either |inner| or |outer|.
  1994. \yskip\noindent The current values of these quantities are referred to
  1995. quite frequently, so they are stored in a separate place instead of in the
  1996. |stack| array. We call the current values |cur_end|, |cur_tok|, and
  1997. |cur_mode|.
  1998. The global variable |stack_ptr| tells how many levels of output are
  1999. currently in progress. The end of output occurs when an |end_translation|
  2000. token is found, so the stack is never empty except when we first begin the
  2001. output process.
  2002. @d inner 0 /* value of |mode| for \cee\ texts within \TeX\ texts */
  2003. @d outer 1 /* value of |mode| for \cee\ texts in modules */
  2004. @<Typed...@>= typedef int mode;
  2005. typedef struct {
  2006.   token_pointer end_field; /* ending location of token list */
  2007.   token_pointer tok_field; /* present location within token list */
  2008.   boolean mode_field; /* interpretation of control tokens */
  2009. } output_state;
  2010. typedef output_state *stack_pointer;
  2011. @ @d cur_end cur_state.end_field /* current ending location in |tok_mem| */
  2012. @d cur_tok cur_state.tok_field /* location of next output token in |tok_mem| */
  2013. @d cur_mode cur_state.mode_field /* current mode of interpretation */
  2014. @d init_stack stack_ptr=stack;cur_mode=outer /* initialize the stack */
  2015. @<Global...@>=
  2016. output_state cur_state; /* |cur_end|, |cur_tok|, |cur_mode| */
  2017. output_state stack[stack_size]; /* info for non-current levels */
  2018. stack_pointer stack_ptr; /* first unused location in the output state stack */
  2019. stack_pointer stack_end=stack+stack_size-1; /* end of |stack| */
  2020. #ifdef STAT
  2021. stack_pointer max_stack_ptr; /* largest value assumed by |stack_ptr| */
  2022. #endif STAT
  2023. @ @<Set init...@>=
  2024. #ifdef STAT
  2025. max_stack_ptr=stack;
  2026. #endif STAT
  2027. @ To insert token-list |p| into the output, the |push_level| subroutine
  2028. is called; it saves the old level of output and gets a new one going.
  2029. The value of |cur_mode| is not changed.
  2030. @c push_level(p) /* suspends the current level */
  2031. text_pointer p;
  2032.   if (stack_ptr==stack_end) overflow("stack");
  2033.   if (stack_ptr>stack) { /* save current state */
  2034.     stack_ptr->end_field=cur_end;
  2035.     stack_ptr->tok_field=cur_tok;
  2036.     stack_ptr->mode_field=cur_mode;
  2037.   stack_ptr++;
  2038. #ifdef STAT
  2039.   if (stack_ptr>max_stack_ptr) max_stack_ptr=stack_ptr;
  2040. #endif STAT
  2041.   cur_tok=*p; cur_end=*(p+1);
  2042. @ Conversely, the |pop_level| routine restores the conditions that were in
  2043. force when the current level was begun. This subroutine will never be
  2044. called when |stack_ptr=1|.
  2045. @c pop_level()
  2046.   cur_end=(--stack_ptr)->end_field;
  2047.   cur_tok=stack_ptr->tok_field; cur_mode=stack_ptr->mode_field;
  2048. @ The |get_output| function returns the next byte of output that is not a
  2049. reference to a token list. It returns the values |identifier| or |res_word|
  2050. or |mod_name| if the next token is to be an identifier (typeset in
  2051. italics), a reserved word (typeset in boldface) or a module name (typeset
  2052. by a complex routine that might generate additional levels of output).
  2053. In these cases |cur_name| points to the identifier or module name in
  2054. question.
  2055. @<Global...@>=
  2056. name_pointer cur_name;
  2057. @ @d res_word 0201 /* returned by |get_output| for reserved words */
  2058. @d mod_name 0200 /* returned by |get_output| for module names */
  2059. @c eight_bits get_output() /* returns the next token of output */
  2060.   sixteen_bits a; /* current item read from |tok_mem| */
  2061.   restart: while (cur_tok==cur_end) pop_level();
  2062.   a=*(cur_tok++);
  2063.   if (a>=0400) {
  2064.     cur_name=a % id_flag + name_dir;
  2065.     switch (a / id_flag) {
  2066.       case 2: return(res_word); /* |a==res_flag+cur_name| */
  2067.       case 3: return(mod_name); /* |a==mod_flag+cur_name| */
  2068.       case 4: push_level(a % id_flag + tok_start); goto restart;
  2069.     /* |a==tok_flag+cur_name| */
  2070.       case 5: push_level(a % id_flag + tok_start); cur_mode=inner; goto restart;
  2071.       /* |a==inner_tok_flag+cur_name| */
  2072.       default: return(identifier); /* |a==id_flag+cur_name| */
  2073.     }
  2074.   return(a);
  2075. @ The real work associated with token output is done by |make_output|.
  2076. This procedure appends an |end_translation| token to the current token list,
  2077. and then it repeatedly calls |get_output| and feeds characters to the output
  2078. buffer until reaching the |end_translation| sentinel. It is possible for
  2079. |make_output| to be called recursively, since a module name may include
  2080. embedded \cee\ text; however, the depth of recursion never exceeds one
  2081. level, since module names cannot be inside of module names.
  2082. A procedure called |output_C| does the scanning, translation, and
  2083. output of \cee\ text within `\pb' brackets, and this procedure uses
  2084. |make_output| to output the current token list. Thus, the recursive call
  2085. of |make_output| actually occurs when |make_output| calls |output_C|
  2086. while outputting the name of a module.
  2087. @^recursion@>
  2088. output_C() /* outputs the current token list */
  2089.   token_pointer save_tok_ptr;
  2090.   text_pointer save_text_ptr;
  2091.   sixteen_bits save_next_control; /* values to be restored */
  2092.   text_pointer p; /* translation of the \cee\ text */
  2093.   save_tok_ptr=tok_ptr; save_text_ptr=text_ptr;
  2094.   save_next_control=next_control; next_control=ignore; p=C_translate();
  2095.   app(p-tok_start+inner_tok_flag);
  2096.   make_output(); /* output the list */
  2097. #ifdef STAT
  2098.   if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
  2099.   if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
  2100. #endif STAT
  2101.   text_ptr=save_text_ptr; tok_ptr=save_tok_ptr; /* forget the tokens */
  2102.   next_control=save_next_control; /* restore |next_control| to original state */
  2103. @ Here is \.{WEAVE}'s major output handler.
  2104. @c make_output() /* outputs the equivalents of tokens */
  2105.   eight_bits a, /* current output byte */
  2106.   b; /* next output byte */
  2107.   int c; /* count of |indent| and |outdent| tokens */
  2108.   ASCII *k, *k_limit; /* indices into |byte_mem| */
  2109.   ASCII *j; /* index into |buffer| */
  2110.   ASCII delim; /* first and last character of string being copied */
  2111.   ASCII *save_loc, *save_limit; /* |loc| and |limit| to be restored */
  2112.   name_pointer cur_mod_name; /* name of module being output */
  2113.   boolean save_mode; /* value of |cur_mode| before a sequence of breaks */
  2114.   app(end_translation); /* append a sentinel */
  2115.   freeze_text; push_level(text_ptr-1);
  2116.   while (1) {
  2117.     a=get_output();
  2118.     reswitch: switch(a) {
  2119.       case end_translation: return;
  2120.       case identifier: case res_word: @<Output an identifier@>; break;
  2121.       case mod_name: @<Output a module name@>; break;
  2122.       case math_bin: case math_rel: @<Output a \.{\\math} operator@>; break;
  2123.       case cancel: c=0; while ((a=get_output())>=indent && a<=big_force) {
  2124.       if (a==indent) c++; if (a==outdent) c--;
  2125.         }
  2126.         @<Output saved |indent| or |outdent| tokens@>;
  2127.         goto reswitch;
  2128.       case big_cancel: c=0;
  2129.     while (((a=get_output())>=indent || a==' ') && a<=big_force) {
  2130.       if (a==indent) c++; if (a==outdent) c--;
  2131.         }
  2132.     @<Output saved...@>;
  2133.     goto reswitch;
  2134.       case indent: case outdent: case opt: case backup: case break_space:
  2135.       case force: case big_force: case preproc_line: @<Output a control,
  2136.         look ahead in case of line breaks, possibly |goto reswitch|@>; break;
  2137.       default: out(a); /* otherwise |a| is an ASCII character */
  2138.     }
  2139. @ An identifier of length one does not have to be enclosed in braces, and it
  2140. looks slightly better if set in a math-italic font instead ofet (slightly
  2141. narrower) text-italic font. Thus we output `\.{\\\v}\.{a}' but
  2142. `\.{\\\\\{aa\}}'.
  2143. @<Output an identifier@>=
  2144. out('\\');
  2145. if (a==identifier)
  2146.   if (length(cur_name)==1) out('|')
  2147. @.\\|@>
  2148.   else out('\\')
  2149. @.\\\\@>
  2150. else out('&') /* |a==res_word| */
  2151. @.\\\&@>
  2152. if (length(cur_name)==1) {
  2153.   if ((cur_name->byte_start)[0]=='_')
  2154.     out('\\');
  2155.   out((cur_name->byte_start)[0]);
  2156. else out_name(cur_name);
  2157. @ @<Output a \....@>=
  2158. if (a==math_bin) out_str("\\mathbin{");
  2159. else out_str("\\mathrel{");
  2160. @ The current mode does not affect the behavior of \.{WEAVE}'s output routine
  2161. except when we are outputting control tokens.
  2162. @<Output a control...@>=
  2163. if (a<break_space || a==preproc_line) {
  2164.   if (cur_mode==outer) {
  2165.     out('\\'); out(a-cancel+'0');
  2166.     if (a==opt) out(get_output()); /* |opt| is followed by a digit */
  2167.     }
  2168.   else if (a==opt) b=get_output(); /* ignore digit following |opt| */
  2169. else @<Look ahead for strongest line break, |goto reswitch|@>
  2170. @ If several of the tokens |break_space|, |force|, |big_force| occur in a
  2171. row, possibly mixed with blank spaces (which are ignored),
  2172. the largest one is used. A line break also occurs in the output file,
  2173. except at the very end of the translation. The very first line break
  2174. is suppressed (i.e., a line break that follows `\.{\\Y\\P}').
  2175. @<Look ahead for st...@>= {
  2176.   b=a; save_mode=cur_mode; c=0;
  2177.   while (1) {
  2178.     a=get_output();
  2179.     if (a==cancel || a==big_cancel) {
  2180.       @<Output saved |indent| or |outdent| tokens@>;
  2181.       goto reswitch; /* |cancel| overrides everything */
  2182.     }
  2183.     if ((a!=' ' && a<indent) || a==backup || a>big_force) {
  2184.       if (save_mode==outer) {
  2185.     if (out_ptr>out_buf+3 && strncmp(out_ptr-3,"\\Y\\P",4)==0)
  2186.       goto reswitch;
  2187.         @<Output saved |indent| or |outdent| tokens@>;
  2188.         out('\\'); out(b-cancel+'0');
  2189.         if (a!=end_translation) finish_line();
  2190.       }
  2191.       else if (a!=end_translation && cur_mode==inner) out(' ');
  2192.       goto reswitch;
  2193.     }
  2194.     if (a==indent) c++;
  2195.     else if (a==outdent) c--;
  2196.     else if (a>b) b=a; /* if |a==' '| we have |a<b| */
  2197. @ @<Output saved...@>=
  2198.   for (;c>0;c--) out_str("\\1");
  2199.   for (;c<0;c++) out_str("\\2");
  2200. @ The remaining part of |make_output| is somewhat more complicated. When we
  2201. output a module name, we may need to enter the parsing and translation
  2202. routines, since the name may contain \cee\ code embedded in
  2203. \pb\ constructions. This \cee\ code is placed at the end of the active
  2204. input buffer and the translation process uses the end of the active
  2205. |tok_mem| area.
  2206. @<Output a module name@>= {
  2207.   out_str("\\X");
  2208. @.\\X@>
  2209.   cur_xref=(xref_pointer)cur_name->xref;
  2210.   if (cur_xref->num>=def_flag) {
  2211.     out_mod(cur_xref->num-def_flag);
  2212.     if (phase==3) {
  2213.       cur_xref=cur_xref->xlink;
  2214.       while (cur_xref->num>=def_flag) {
  2215.     out_str(", ");
  2216.         out_mod(cur_xref->num-def_flag);
  2217.       cur_xref=cur_xref->xlink;
  2218.       }
  2219.     }
  2220.   else out('0'); /* output the module number, or zero if it was undefined */
  2221.   out(':'); @<Output the text of the module name@>;
  2222.   out_str("\\X");
  2223. @ @<Output the text...@>=
  2224. k=cur_name->byte_start; k_limit=(cur_name+1)->byte_start;
  2225. cur_mod_name=cur_name;
  2226. while (k<k_limit) {
  2227.   b=*(k++);
  2228.   if (b=='@@') @<Skip next character, give error if not `\.{@@}'@>;
  2229.   if (b!='|') out(b)
  2230.   else {
  2231.     @<Copy the \cee\ text into the |buffer| array@>;
  2232.     save_loc=loc; save_limit=limit; loc=limit+2; limit=j+1;
  2233.     *limit='|'; output_C();
  2234.     loc=save_loc; limit=save_limit;
  2235. @ @<Skip next char...@>=
  2236. if (*k++!='@@') {
  2237.   printf("\n! Illegal control code in section name: <");
  2238. @.Illegal control code...@>
  2239.   print_id(cur_mod_name); printf("> "); mark_error;
  2240. @ The \cee\ text enclosed in \pb\ should not contain `\.{\v}' characters,
  2241. except within strings. We put a `\.{\v}' at the front of the buffer, so that an
  2242. error message that displays the whole buffer will look a little bit sensible.
  2243. The variable |delim| is zero outside of strings, otherwise it
  2244. equals the delimiter that began the string being copied.
  2245. @<Copy the \cee\ text into...@>=
  2246. j=limit+1; *j='|'; delim=0;
  2247. while (1) {
  2248.   if (k>=k_limit) {
  2249.     printf("\n! C text in section name didn't end: <");
  2250. @.C text...didn't end@>
  2251.     print_id(cur_mod_name); printf("> "); mark_error; break;
  2252.   b=*(k++);
  2253.   if (b=='@@') @<Copy a control code into the buffer@>
  2254.   else {
  2255.     if (b=='\'' || b=='"')
  2256.       if (delim==0) delim=b;
  2257.       else if (delim==b) delim=0;
  2258.     if (b!='|' || delim!=0) {
  2259.       if (j>buffer+long_buf_size-3) overflow("buffer");
  2260.       *(++j)=b;
  2261.     }
  2262.     else break;
  2263. @ @<Copy a control code into the buffer@>= {
  2264.   if (j>buffer+long_buf_size-4) overflow("buffer");
  2265.   *(++j)='@@'; *(++j)=*(k++);
  2266. @* Phase two processing.
  2267. We have assembled enough pieces of the puzzle in order to be ready to specify
  2268. the processing in \.{WEAVE}'s main pass over the source file. Phase two
  2269. is analogous to phase one, except that more work is involved because we must
  2270. actually output the \TeX\ material instead of merely looking at the
  2271. \.{WEB} specifications.
  2272. @c phase_two() {
  2273. reset_input(); printf("\nWriting the output file...");
  2274. module_count=0; copy_limbo();
  2275. math_flag=0;
  2276. finish_line(); flush_buffer(out_buf,0); /* insert a blank line, it looks nice */
  2277. while (!input_has_ended) @<Translate the current module@>;
  2278. @ The output file will contain the control sequence \.{\\Y} between non-null
  2279. sections of a module, e.g., between the \TeX\ and definition parts if both
  2280. are nonempty. This puts a little white space between the parts when they are
  2281. printed. However, we don't want \.{\\Y} to occur between two definitions
  2282. within a single module. The variables |out_line| or |out_ptr| will
  2283. change if a section is non-null, so the following macros `|save_position|'
  2284. and `|emit_space_if_needed|' are able to handle the situation:
  2285. @d save_position save_line=out_line; save_place=out_ptr
  2286. @d emit_space_if_needed if (save_line!=out_line || save_place!=out_ptr)
  2287.   out_str("\\Y");
  2288. @.\\Y@>
  2289. @<Global...@>=
  2290. int save_line; /* former value of |out_line| */
  2291. ASCII *save_place; /* former value of |out_ptr| */
  2292. @ @<Translate the current module@>= {
  2293.   module_count++;
  2294.   @<Output the code for the beginning of a new module@>;
  2295.   save_position;
  2296.   @<Translate the \TeX\ part of the current module@>;
  2297.   @<Translate the definition part of the current module@>;
  2298.   @<Translate the \cee\ part of the current module@>;
  2299.   @<Show cross-references to this module@>;
  2300.   @<Output the code for the end of a module@>;
  2301. @ Modules beginning with the \.{WEB} control sequence `\.{@@\ }' start in the
  2302. output with the \TeX\ control sequence `\.{\\M}', followed by the module
  2303. number. Similarly, `\.{@@*}' modules lead to the control sequence `\.{\\N}'.
  2304. If this is a changed module, we put \.{*} just before the module number.
  2305. @<Output the code for the beginning...@>=
  2306. if (*(loc-1)!='*') out_str("\\M");
  2307. @.\\M@>
  2308. else {
  2309.   out_str("\\N");
  2310. @.\\N@>
  2311.   printf("*%d",module_count); update_terminal; /* print a progress report */
  2312. out_mod(module_count); out_str(". ");
  2313. @ In the \TeX\ part of a module, we simply copy the source text, except that
  2314. index entries are not copied and \cee\ text within \pb\ is translated.
  2315. @<Translate the \T...@>= do {
  2316.   next_control=copy_TeX();
  2317.   switch (next_control) {
  2318.     case '|': init_stack; output_C(); break;
  2319.     case '@@': out('@@'); break;
  2320.     case TeX_string: case xref_roman: case xref_wildcard: case xref_typewriter:
  2321.     case module_name: loc-=2; next_control=get_next(); /* skip to \.{@@>} */
  2322.       if (next_control==TeX_string)
  2323.         err_print("! TeX string should be in C text only"); break;
  2324. @.TeX string should be...@>
  2325.     case thin_space: case math_break:
  2326.     case line_break: case big_line_break: case no_line_break: case join:
  2327.     case pseudo_semi: err_print("! You can't do that in TeX text"); break;
  2328. @.You can't do that...@>
  2329. } while (next_control<format);
  2330. @ When we get to the following code we have |next_control>=format|, and
  2331. the token memory is in its initial empty state.
  2332. @<Translate the d...@>=
  2333. if (next_control<=definition) { /* definition part non-empty */
  2334.   emit_space_if_needed; save_position;
  2335. while (next_control<=definition) { /* |format| or |definition| */
  2336.   init_stack;
  2337.   if (next_control==definition) @<Start a macro definition@>@;
  2338.   else @<Start a format definition@>;
  2339.   outer_parse(); finish_C();
  2340. @ The |finish_C| procedure outputs the translation of the current
  2341. scraps, preceded by the control sequence `\.{\\P}' and followed by the
  2342. control sequence `\.{\\par}'. It also restores the token and scrap
  2343. memories to their initial empty state.
  2344. A |force| token is appended to the current scraps before translation
  2345. takes place, so that the translation will normally end with \.{\\6} or
  2346. \.{\\7} (the \TeX\ macros for |force| and |big_force|). This \.{\\6} or
  2347. \.{\\7} is replaced by the concluding \.{\\par} or by \.{\\Y\\par}.
  2348. @c finish_C() /* finishes a definition or a \cee\ part */
  2349.   text_pointer p; /* translation of the scraps */
  2350.   out_str("\\P"); app_tok(force); app_scrap(ignore_scrap,no_math);
  2351.   p=translate();
  2352. @.\\P@>
  2353.   app(p-tok_start+tok_flag); make_output(); /* output the list */
  2354.   if (out_ptr>out_buf+1)
  2355.     if (*(out_ptr-1)=='\\')
  2356. @.\\6@>
  2357. @.\\7@>
  2358. @.\\Y@>
  2359.       if (*out_ptr=='6') out_ptr-=2;
  2360.       else if (*out_ptr=='7') *out_ptr='Y';
  2361.   out_str("\\par"); finish_line();
  2362. #ifdef STAT
  2363.   if (text_ptr>max_text_ptr) max_text_ptr=text_ptr;
  2364.   if (tok_ptr>max_tok_ptr) max_tok_ptr=tok_ptr;
  2365.   if (scrap_ptr>max_scr_ptr) max_scr_ptr=scrap_ptr;
  2366. #endif STAT
  2367.   tok_ptr=tok_mem+1; text_ptr=tok_start+1; scrap_ptr=scrap_info;
  2368.     /* forget the tokens and the scraps */
  2369. @ Keeping in line with the conventions of the \cee\ preprocessor (and
  2370. otherwise contrary to the rules of \.{WEB}) we distinguish here
  2371. between the case that `\.(' immediately follows an identifier and the
  2372. case that the two are separated by a space.  In the latter case, and
  2373. if the identifier is not followed by `\.(' at all, the replacement
  2374. text starts immediately after the identifier.  In the former case,
  2375. it starts after we scan the matching `\.)'.
  2376. @<Start a macro...@>= {
  2377.   app(backup); app_str("\\D"); /* this will produce `\&{define}' */
  2378. @.\\D@>
  2379.   if ((next_control=get_next())!=identifier)
  2380.     err_print("! Improper macro definition");
  2381. @.Improper macro definition@>
  2382.   else {
  2383.     app('$'); app(id_flag+id_lookup(id_first, id_loc,normal)-name_dir);
  2384.     if (*loc=='(')
  2385.   reswitch: switch (next_control=get_next()) {
  2386.       case '(': case ',': app(next_control); goto reswitch;
  2387.       case identifier: app(id_flag+id_lookup(id_first, id_loc,normal)-name_dir); goto reswitch;
  2388.       case ')': app(next_control); next_control=get_next(); break;
  2389.       default: err_print("! Improper macro definition"); break;
  2390.     }
  2391.     else next_control=get_next();
  2392.     app('$'); app(break_space);
  2393.     app_scrap(ignore_scrap,no_math); /* scrap won't take part in the parsing */
  2394. @ @<Start a format...@>= {
  2395.   app_str("\\F"); /* this will produce `\&{format}' */
  2396. @.\\F@>
  2397.   next_control=get_next();
  2398.   if (next_control==identifier) {
  2399.     app(break_space);
  2400.     app(id_flag+id_lookup(id_first, id_loc,normal)-name_dir);
  2401.     app(break_space); /* this is syntactically separate from what follows */
  2402.     next_control=get_next();
  2403.     if (next_control==identifier) {
  2404.       app(id_flag+id_lookup(id_first, id_loc,normal)-name_dir);
  2405.       app_scrap(exp,0); app_scrap(semi,0);
  2406.       next_control=get_next();
  2407.     }
  2408.   if (scrap_ptr!=scrap_info+2) err_print("! Improper format definition");
  2409. @.Improper format definition@>
  2410. @ Finally, when the \TeX\ and definition parts have been treated, we have
  2411. |next_control>=begin_C|. We will make the global variable |this_module|
  2412. point to the current module name, if it has a name.
  2413. @<Global...@>=
  2414. name_pointer this_module; /* the current module name, or zero */
  2415. @ @<Translate the \cee...@>=
  2416. this_module=name_dir;
  2417. if (next_control<=module_name) {
  2418.   emit_space_if_needed; init_stack;
  2419.   if (next_control==begin_C) next_control=get_next();
  2420.   else {
  2421.     this_module=cur_module;
  2422.     @<Check that |=| or |==| follows this module name, and
  2423.       emit the scraps to start the module definition@>;
  2424.   while  (next_control<=module_name) {
  2425.     outer_parse();
  2426.     @<Emit the scrap for a module name if present@>;
  2427.   finish_C();
  2428. @ @<Check that |=|...@>=
  2429. do next_control=get_next();
  2430.   while (next_control=='+'); /* allow optional `\.{+=}' */
  2431. if (next_control!='=' && next_control!=eq_eq)
  2432.   err_print("! You need an = sign after the section name");
  2433. @.You need an = sign...@>
  2434.   else next_control=get_next();
  2435. if (out_ptr>out_buf+1 && *out_ptr=='Y' && *(out_ptr-1)=='\\') app(backup);
  2436.     /* the module name will be flush left */
  2437. @.\\Y@>
  2438. app(mod_flag+this_module-name_dir);
  2439. cur_xref=(xref_pointer)this_module->xref;
  2440. app_str("${}");
  2441. if (cur_xref->num!=module_count+def_flag) {
  2442.   app_str("+"); /*module name is multiply defined*/
  2443.   this_module=name_dir; /*so we won't give cross-reference info here*/
  2444. app_str("\\S"); /* output an equivalence sign */
  2445. @.\\S@>
  2446. app_str("{}$");
  2447. app(force); app_scrap(stmt,2); /* this forces a line break unless `\.{@@+}' follows */
  2448. @ @<Emit the scrap...@>=
  2449. if (next_control<module_name) {
  2450.   err_print("! You can't do that in C text");
  2451. @.You can"t do that...@>
  2452.   next_control=get_next();
  2453. else if (next_control==module_name) {
  2454.   app(mod_flag+cur_module-name_dir); app_scrap(exp,0); next_control=get_next();
  2455. @ Cross references relating to a named module are given after the module ends.
  2456. @<Show cross...@>=
  2457. if (this_module>name_dir) {
  2458.   @<Rearrange the list pointed to by |cur_xref|@>;
  2459.   footnote(def_flag); footnote(0);
  2460. @ To rearrange the order of the linked list of cross-references, we need
  2461. four more variables that point to cross-reference entries.  We'll end up
  2462. with a list pointed to by |cur_xref|.
  2463. @<Global...@>=
  2464. xref_pointer next_xref, this_xref, first_xref, mid_xref;
  2465.   /* pointer variables for rearranging a list */
  2466. @ We want to rearrange the cross-reference list so that all the entries with
  2467. |def_flag| come first, in ascending order; then come all the other
  2468. entries, in ascending order.  There may be no entries in either one or both
  2469. of these categories.
  2470. @<Rearrange the list...@>=
  2471.   first_xref=(xref_pointer)this_module->xref;
  2472.   this_xref=first_xref->xlink; /* bypass current module number */
  2473.   if (this_xref->num>def_flag) {
  2474.     mid_xref=this_xref; cur_xref=0; /* this value doesn't matter */
  2475.   do {
  2476.     next_xref=this_xref->xlink; this_xref->xlink=cur_xref;
  2477.     cur_xref=this_xref; this_xref=next_xref;
  2478.   } while (this_xref->num>def_flag);
  2479.   first_xref->xlink=cur_xref;
  2480. else mid_xref=xmem; /* first list null */
  2481. cur_xref=xmem;
  2482. while (this_xref!=xmem) {
  2483.   next_xref=this_xref->xlink; this_xref->xlink=cur_xref;
  2484.   cur_xref=this_xref; this_xref=next_xref;
  2485. if (mid_xref>xmem) mid_xref->xlink=cur_xref;
  2486. else first_xref->xlink=cur_xref;
  2487. cur_xref=first_xref->xlink;
  2488. @ The |footnote| procedure gives cross-reference information about
  2489. multiply defined module names (if the |flag| parameter is |def_flag|), or about
  2490. the uses of a module name (if the |flag| parameter is zero). It assumes that
  2491. |cur_xref| points to the first cross-reference entry of interest, and it
  2492. leaves |cur_xref| pointing to the first element not printed.  Typical outputs:
  2493. `\.{\\A\ section 101.}'; `\.{\\U\ sections 370 and 1009.}';
  2494. `\.{\\A\ sections 8, 27\\*, and 64.}'.
  2495. @c footnote(flag) /* outputs module cross-references */
  2496. sixteen_bits flag;
  2497.   xref_pointer q; /* cross-reference pointer variable */
  2498.   if (cur_xref->num<=flag) return;
  2499.   finish_line(); out('\\');
  2500. @.\\A@>
  2501. @.\\U@>
  2502.   if (flag==0) out('U')@+else out('A');
  2503.   out_str(" section");
  2504.   @<Output all the module numbers on the reference list |cur_xref|@>;
  2505.   out('.');
  2506. @ The following code distinguishes three cases, according as the number
  2507. of cross-references is one, two, or more than two. Variable |q| points
  2508. to the first cross-reference, and the last link is a zero.
  2509. @<Output all the module numbers...@>=
  2510. q=cur_xref; if (q->xlink->num>flag) out('s'); /* plural */
  2511. out('~');
  2512. while (1) {
  2513.   out_mod(cur_xref->num-flag);
  2514.   cur_xref=cur_xref->xlink; /* point to the next cross-reference to output */
  2515.   if (cur_xref->num<=flag) break;
  2516.   if (cur_xref->xlink->num>flag || cur_xref!=q->xlink) out(',');
  2517.     /* not the last of two */
  2518.   out(' ');
  2519.   if (cur_xref->xlink->num<=flag) out_str("and~"); /* the last */
  2520. @ @<Output the code for the end of a module@>=
  2521. out_str("\\fi"); finish_line();
  2522. @.\\fi@>
  2523. flush_buffer(out_buf,0); /* insert a blank line, it looks nice */
  2524. @* Phase three processing.
  2525. We are nearly finished! \.{WEAVE}'s only remaining task is to write out the
  2526. index, after sorting the identifiers and index entries.
  2527. If the user has set the |no_xref| flag (the |-x| option on the command line),
  2528. just finish off the page, omitting the index, module name list, and table of
  2529. contents.
  2530. @<Glob...@>=
  2531. extern int no_xref;
  2532. @ @c phase_three() {
  2533. if (no_xref) {
  2534.   finish_line();
  2535.   out_str("\\vfill\\end");
  2536.   finish_line();
  2537. else {
  2538.   phase=3; printf("\nWriting the index...");
  2539.   if (change_exists) {
  2540.     finish_line(); @<Tell about changed modules@>;
  2541.   finish_line(); out_str("\\inx"); finish_line();
  2542. @.\\inx@>
  2543.   @<Do the first pass of sorting@>;
  2544.   @<Sort and output the index@>;
  2545.   out_str("\\fin"); finish_line();
  2546. @.\\fin@>
  2547.   @<Output all the module names@>;
  2548.   out_str("\\con"); finish_line();
  2549. @.\\con@>
  2550. printf("Done.");
  2551. check_complete(); /* was all of the change file used? */
  2552. @ Just before the index comes a list of all the changed modules, including
  2553. the index module itself.
  2554. @<Global...@>=
  2555. sixteen_bits k_module; /* runs through the modules */
  2556. @ @<Tell about changed modules@>= {
  2557.   /* remember that the index is already marked as changed */
  2558.   k_module=0;
  2559.   while (!changed_module[++k_module]);
  2560.   out_str("\\ch ");
  2561.   out_mod(k_module);
  2562.   while (1) {
  2563.     while (!changed_module[++k_module]);
  2564.     out_str(", "); out_mod(k_module);
  2565.     if (k_module==module_count) break;
  2566.   out('.');
  2567. @ A left-to-right radix sorting method is used, since this makes it easy to
  2568. adjust the collating sequence and since the running time will be at worst
  2569. proportional to the total length of all entries in the index. We put the
  2570. identifiers into 102 different lists based on their first characters.
  2571. (Uppercase letters are put into the same list as the corresponding lowercase
  2572. letters, since we want to have `$t<\\{TeX}<\&{to}$'.) The
  2573. list for character |c| begins at location |bucket[c]| and continues through
  2574. the |blink| array.
  2575. @<Global...@>=
  2576. name_pointer bucket[128];
  2577. name_pointer next_name; /* successor of |cur_name| when sorting */
  2578. hash_pointer h; /* index into |hash| */
  2579. name_pointer blink[max_names]; /* links in the buckets */
  2580. @ To begin the sorting, we go through all the hash lists and put each entry
  2581. having a nonempty cross-reference list into the proper bucket.
  2582. @<Do the first pass...@>= {
  2583. int c;
  2584. for (c=0; c<=127; c++) bucket[c]=NULL;
  2585. for (h=hash; h<=hash_end; h++) {
  2586.   next_name=*h;
  2587.   while (next_name) {
  2588.     cur_name=next_name; next_name=cur_name->link;
  2589.     if (cur_name->xref!=(char*)xmem) {
  2590.       c=(cur_name->byte_start)[0];
  2591.       if (c<='Z' && c>='A') c=c+040;
  2592.       blink[cur_name-name_dir]=bucket[c]; bucket[c]=cur_name;
  2593.     }
  2594. @ During the sorting phase we shall use the |cat| and |trans| arrays from
  2595. \.{WEAVE}'s parsing algorithm and rename them |depth| and |head|. They now
  2596. represent a stack of identifier lists for all the index entries that have
  2597. not yet been output. The variable |sort_ptr| tells how many such lists are
  2598. present; the lists are output in reverse order (first |sort_ptr|, then
  2599. |sort_ptr-1|, etc.). The |j|th list starts at |head[j]|, and if the first
  2600. |k| characters of all entries on this list are known to be equal we have
  2601. |depth[j]=k|.
  2602. @ @<Rest of |trans_plus| union@>=
  2603. name_pointer Head;
  2604. @d depth cat /* reclaims memory that is no longer needed for parsing */
  2605. @d head trans_plus.Head /* ditto */
  2606. @d sort_pointer scrap_pointer /* ditto */
  2607. @d sort_ptr scrap_ptr /* ditto */
  2608. @d max_sorts max_scraps /* ditto */
  2609. @<Global...@>=
  2610. eight_bits cur_depth; /* depth of current buckets */
  2611. ASCII *cur_byte; /* index into |byte_mem| */
  2612. sixteen_bits cur_val; /* current cross-reference number */
  2613. #ifdef STAT
  2614. sort_pointer max_sort_ptr; /* largest value of |sort_ptr| */
  2615. #endif STAT
  2616. @ @<Set init...@>=
  2617. #ifdef STAT
  2618. max_sort_ptr=scrap_info;
  2619. #endif STAT
  2620. @ The desired alphabetic order is specified by the |collate| array; namely,
  2621. |collate[0]<collate[1]<@t$\cdots$@><collate[100]|.
  2622. @<Global...@>=
  2623. ASCII collate[102]; /* collation order */
  2624. @ We use the order $\hbox{null}<\.\ <\hbox{other characters}<{}$\.\_${}<
  2625. \.A=\.a<\cdots<\.Z=\.z<\.0<\cdots<\.9.$
  2626. @<Set init...@>=
  2627. collate[0]=0; strcpy(collate+1," \1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\
  2628. \20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37\
  2629. !\42#$%&'()*+,-./:;<=>?@@[\\]^`{|}~_\
  2630. abcdefghijklmnopqrstuvwxyz0123456789");
  2631. @ Procedure |unbucket| goes through the buckets and adds nonempty lists
  2632. to the stack, using the collating sequence specified in the |collate| array.
  2633. The parameter to |unbucket| tells the current depth in the buckets.
  2634. Any two sequences that agree in their first 255 character positions are
  2635. regarded as identical.
  2636. @d infinity 255 /* $\infty$ (approximately) */
  2637. @c unbucket(d) /* empties buckets having depth |d| */
  2638. eight_bits d;
  2639.   int c;  /* index into |bucket|; cannot be an ASCII because of sign
  2640.     comparison below*/
  2641.   for (c=100; c>= 0; c--) if (bucket[collate[c]]) {
  2642.     if (sort_ptr>=scrap_info_end) overflow("sorting");
  2643.     sort_ptr++;
  2644. #ifdef STAT
  2645.     if (sort_ptr>max_sort_ptr) max_sort_ptr=sort_ptr;
  2646. #endif STAT
  2647.     if (c==0) sort_ptr->depth=infinity;
  2648.     else sort_ptr->depth=d;
  2649.     sort_ptr->head=bucket[collate[c]]; bucket[collate[c]]=NULL;
  2650. @ @<Sort and output...@>=
  2651. sort_ptr=scrap_info; unbucket(1);
  2652. while (sort_ptr>scrap_info) {
  2653.   cur_depth=sort_ptr->depth;
  2654.   if (blink[sort_ptr->head-name_dir]==0 || cur_depth==infinity)
  2655.     @<Output index entries for the list at |sort_ptr|@>@;
  2656.   else @<Split the list at |sort_ptr| into further lists@>;
  2657. @ @<Split the list...@>= {
  2658.   ASCII c;
  2659.   next_name=sort_ptr->head;
  2660.   do {
  2661.     cur_name=next_name; next_name=blink[cur_name-name_dir];
  2662.     cur_byte=cur_name->byte_start+cur_depth;
  2663.     if (cur_byte==(cur_name+1)->byte_start) c=0; /* hit end of the name */
  2664.     else {
  2665.       c=*cur_byte;
  2666.       if (c<='Z' && c>='A') c=c+040;
  2667.     }
  2668.   blink[cur_name-name_dir]=bucket[c]; bucket[c]=cur_name;
  2669.   } while (next_name);
  2670.   --sort_ptr; unbucket(cur_depth+1);
  2671. @ @<Output index...@>= {
  2672.   cur_name=sort_ptr->head;
  2673.   do {
  2674.     out_str("\\:");
  2675. @.\\:@>
  2676.     @<Output the name at |cur_name|@>;
  2677.     @<Output the cross-references at |cur_name|@>;
  2678.     cur_name=blink[cur_name-name_dir];
  2679.   } while (cur_name);
  2680.   --sort_ptr;
  2681. @ @<Output the name...@>=
  2682. switch (cur_name->ilk) {
  2683.   case normal: if (length(cur_name)==1) out_str("\\|");
  2684.     else out_str("\\\\"); break;
  2685. @.\\|@>
  2686. @.\\\\@>
  2687.   case roman: break;
  2688.   case wildcard: out_str("\\9"); break;
  2689. @.\\9@>
  2690.   case typewriter: out_str("\\."); break;
  2691. @.\\.@>
  2692.   default: out_str("\\&");
  2693. @.\\\&@>
  2694. out_name(cur_name);
  2695. @ Section numbers that are to be underlined are enclosed in
  2696. `\.{\\[}$\,\ldots\,$\.]'.
  2697. @<Output the cross-references...@>=
  2698. @<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>;
  2699.   out_str(", "); cur_val=cur_xref->num;
  2700.   if (cur_val<def_flag) out_mod(cur_val);
  2701.   else {out_str("\\["); out_mod(cur_val-def_flag); out(']');}
  2702. @.\\[@>
  2703.   cur_xref=cur_xref->xlink;
  2704. } while (cur_xref!=xmem);
  2705. out('.'); finish_line();
  2706. @ List inversion is best thought of as popping elements off one stack and
  2707. pushing them onto another. In this case |cur_xref| will be the head of
  2708. the stack that we push things onto.
  2709. @<Invert the cross-reference list at |cur_name|, making |cur_xref| the head@>=
  2710. this_xref=(xref_pointer)cur_name->xref; cur_xref=xmem;
  2711.   next_xref=this_xref->xlink; this_xref->xlink=cur_xref;
  2712.   cur_xref=this_xref; this_xref=next_xref;
  2713. } while (this_xref!=xmem);
  2714. @ The following recursive procedure walks through the tree of module names and
  2715. prints them.
  2716. @^recursion@>
  2717. @c mod_print(p) /* print all module names in subtree |p| */
  2718. name_pointer p;
  2719.   if (p) {
  2720.     mod_print(p->llink); out_str("\\:");
  2721. @.\\:@>
  2722.     tok_ptr=tok_mem+1; text_ptr=tok_start+1; scrap_ptr=scrap_info; init_stack;
  2723.     app(p-name_dir+mod_flag); make_output();
  2724.     footnote(0); /* |cur_xref| was set by |make_output| */
  2725.     finish_line();@/
  2726.     mod_print(p->rlink);
  2727. @ @<Output all the module names@>=mod_print(root)
  2728. #ifdef STAT
  2729. print_stats() {
  2730.   printf("\nMemory usage statistics:\n");
  2731.   printf("%d names (out of %d)\n",name_ptr-name_dir,max_names);
  2732.   printf("%d cross-references (out of %d)\n",xref_ptr-xmem,max_refs);
  2733.   printf("%d bytes (out of %d)\n",byte_ptr-byte_mem,max_bytes);
  2734.   printf("Parsing:\n");
  2735.   printf("%d scraps (out of %d)\n",max_scr_ptr-scrap_info,max_scraps);
  2736.   printf("%d texts (out of %d)\n",max_text_ptr-tok_start,max_texts);
  2737.   printf("%d tokens (out of %d)\n",max_tok_ptr-tok_mem,max_toks);
  2738.   printf("%d levels (out of %d)\n",max_stack_ptr-stack,stack_size);
  2739.   printf("Sorting:\n");
  2740.   printf("%d levels (out of %d)\n",max_sort_ptr-scrap_info,max_scraps);
  2741. #endif
  2742. @* Index.
  2743. If you have read and understood the code for Phase III above, you know what
  2744. is in this index and how it got here. All modules in which an identifier is
  2745. used are listed with that identifier, except that reserved words are
  2746. indexed only when they appear in format definitions, and the appearances
  2747. of identifiers in module names are not indexed. Underlined entries
  2748. correspond to where the identifier was declared. Error messages, control
  2749. sequences put into the output, and a few
  2750. other things like ``recursion'' are indexed here too.
  2751.